For example if I have a list like this:
List1 =[7,6,9]
List1 = List1.sort()
list.sort()
对列表进行就地排序并返回None
,因此您实际上将该返回值分配给List1
, ie None
。
>>> List1 =[7,6,9]
>>> repr(List1.sort())
'None' #return Value of list.sort
>>> List1 #though list is sorted
[6, 7, 9]
另一方面,内置函数sorted
返回一个新的排序列表:
>>> List1 =[7,6,9]
>>> sorted(List1)
[6, 7, 9]
>>> List1 #List1 is not affected
[7, 6, 9]
您可以将结果分配回sorted
to List1
,但这没有任何意义,因为list.sort
会在更短的时间内做同样的事情。
>>> List1 = sorted(List1)
>>> List1
[6, 7, 9]
虽然上面的代码类似于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])
时间比较:
>>> 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
因此,sorted
仅当您不想影响原始列表并且想要将该列表的排序版本分配给其他变量时才应使用。
除了列表之外,其他数据结构(如set、tuples、dicts等)没有自己的.sort()
方法,因此sorted
您只能在其中使用。
>>> s = {1,5,3,6} # set
>>> sorted(s)
[1, 3, 5, 6]
帮助sorted
:
>>> print sorted.__doc__
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list