Ash*_*ary 14

list.sort()对列表进行就地排序并返回None,因此您实际上是将该返回值分配给List1,即None.

>>> List1 =[7,6,9]
>>> repr(List1.sort())
'None'                     #return Value of list.sort
>>> List1                  #though list is sorted
[6, 7, 9]
Run Code Online (Sandbox Code Playgroud)

另一方面,内置函数sorted返回一个新的排序列表:

>>> List1 =[7,6,9]
>>> sorted(List1)
[6, 7, 9]
>>> List1           #List1 is not affected
[7, 6, 9]
Run Code Online (Sandbox Code Playgroud)

你可以将结果分配sortedList1,但这没有任何意义,因为它list.sort会在较短的时间内做同样的事情.

>>> List1 = sorted(List1)
>>> List1
[6, 7, 9]
Run Code Online (Sandbox Code Playgroud)

虽然上面的代码类似list.sort,但实际上它有点不同,因为它返回新的列表.例:

>>> List1 =[7,6,9]
>>> List2 = List1         # both List1, List2 point to the same object [7, 6, 9]
>>> List1.sort()          # sort List1 in-place, affects the original object
>>> List1, List2
([6, 7, 9], [6, 7, 9])    # both variables still point to the same list

>>> List1 =[7,6,9]
>>> List2 = List1         #same as above
>>> List1 = sorted(List1) #sorted returns a new list, so List1 now points to this new list 
>>> List1, List2          #List2 is still unchanged
([6, 7, 9], [7, 6, 9])
Run Code Online (Sandbox Code Playgroud)

时间比较:

>>> from random import shuffle

>>> lis = range(10**5)
>>> shuffle(lis)
>>> %timeit lis.sort()
1 loops, best of 3: 9.9 ms per loop

>>> lis = range(10**5)
>>> shuffle(lis)
>>> %timeit sorted(lis)
1 loops, best of 3: 95.9 ms per loop
Run Code Online (Sandbox Code Playgroud)

因此,sorted只有在您不想影响原始列表并希望将该列表的排序版本分配给其他变量时才应使用.

除了列表之外,其他数据结构如set,tuples,dicts.sort()等都没有自己的方法,所以sorted你可以在那里使用它.

>>> s = {1,5,3,6}  # set
>>> sorted(s)
[1, 3, 5, 6]
Run Code Online (Sandbox Code Playgroud)

帮助sorted:

>>> print sorted.__doc__
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
Run Code Online (Sandbox Code Playgroud)


Ter*_*ryA 6

.sort()对列表进行排序.它不会返回新列表.事实上,因为默认情况下它没有返回任何内容,所以它返回None.

如果要返回已排序的列表,可以使用sorted():

List1 = sorted(List1)
Run Code Online (Sandbox Code Playgroud)

  • 使用`List1 = sorted(List1)`代替`List1.sort()`通常没有意义.唯一的区别是它将原始内容与排序列表分离,但如果List1是List的唯一引用,那么未排序的内容将只是GC'd (4认同)
  • @Kiro嗯,我其实并不知道这件事.每天学些新东西... (3认同)
  • 您可以向`.sort()`添加额外的参数. (2认同)