>>> 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
list.sort()
对列表进行适当排序并返回None
,因此实际上是将返回值赋给List1
,即None
。在另一方面,内置函数
^{pr2}$sorted
返回一个新的排序列表:您可以将}将在更短的时间内完成相同的操作。在
sorted
的结果分配给List1
,但这没有意义,因为{虽然上面的代码类似于
list.sort
,但实际上它有点不同,因为它返回新的list。示例:时间比较:
因此,
sorted
应该只在您不想影响原始列表并希望将该列表的排序版本分配给其他变量时使用。在除了列出其他数据结构,如set,元组,dicts等等,没有它们自己的
.sort()
方法,因此sorted
是唯一可以在那里使用的东西。在关于
sorted
的帮助:^{} 对列表进行适当排序。它不返回新列表。事实上,由于默认情况下不返回任何内容,它返回
None
。在如果要返回已排序的列表,可以使用^{} :
相关问题 更多 >
编程相关推荐