search

Home  >  Q&A  >  body text

python2.7 - Python:为什么不可以这样:print list1.sort(),而是先:list1.sort()再print list1?

迷茫迷茫2901 days ago641

reply all(6)I'll reply

  • 阿神

    阿神2017-04-17 15:43:36

    Because the type returned by the sort method of List is <type 'NoneType'>, your print here is not list1.

    >>> list1=[3,2,5,6,1]
    >>> print type(list1.sort())
    <type 'NoneType'>

    reply
    0
  • 迷茫

    迷茫2017-04-17 15:43:36

    Because sort has no return value

    reply
    0
  • PHPz

    PHPz2017-04-17 15:43:36

    I just encountered this problem recently. The reason is that list1.sort() only sorts the elements in list1, and then returns NoneType. If you want to get the sorted list directly, you should use the sorted function.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:43:36

    You can use sorted

    >>> list1=[3,2,5,6,1]
    >>> print sorted(list1)
    [1, 2, 3, 5, 6]

    reply
    0
  • 黄舟

    黄舟2017-04-17 15:43:36

    sorted returns a new list. sort sorts in place.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:43:36

    Because the function of list.sort() is to sort the elements of the list, rather than turning list.sort() itself into a sorted list

    reply
    0
  • Cancelreply