例如,如果我有这样一个列表:
List1 =[7,6,9]
List1 = List1.sort()
最佳答案
list.sort()
就地对列表进行排序并返回 None
,因此您实际上是将该返回值分配给 List1
,即 无
。
>>> 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
的结果分配回 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]
关于排序
的帮助:
>>> print sorted.__doc__
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
关于python - 谁能解释为什么这种排序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141255/