谁能解释为什么这种排序不起作用? [英] Can anyone explain why this sorting won't work?
问题描述
例如,如果我有一个这样的列表:
For example if I have a list like this:
List1 =[7,6,9]
List1 = List1.sort()
推荐答案
list.sort()
对列表进行原位排序并返回None
,因此您实际上是将该返回值分配给List1
,即None
.
list.sort()
sorts the list in-place and returns None
, so you were actually assigning that return value to List1
, i.e None
.
>>> List1 =[7,6,9]
>>> repr(List1.sort())
'None' #return Value of list.sort
>>> List1 #though list is sorted
[6, 7, 9]
另一方面,内置函数sorted
返回一个新排序列表:
On the other hand the built-in function sorted
returns a new sorted list:
>>> List1 =[7,6,9]
>>> sorted(List1)
[6, 7, 9]
>>> List1 #List1 is not affected
[7, 6, 9]
您可以将sorted
的结果分配回List1
,但这没有任何意义,因为list.sort
可以在更少的时间内完成相同的操作.
You can assign back the result of sorted
to List1
, but this makes no sense as list.sort
will do the same thing and in lesser time.
>>> List1 = sorted(List1)
>>> List1
[6, 7, 9]
尽管上面的代码与list.sort
类似,但实际上有所不同,因为它返回了新列表.示例:
Though the above code was similar to list.sort
, but actually it's a bit different because it returns new list. Example:
>>> 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
.
So, sorted
should be used only when you don't want to affect the original list and want to assign the sorted version of that list to some other variable.
除了列出其他数据结构外,例如 set ,元组,字典等,没有自己的.sort()
方法,因此sorted
是您唯一可以在此处使用的东西.
Apart from lists other data-structures like set, tuples, dicts,etc don't have their own .sort()
method, so sorted
is the only thing you can use there.
>>> 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
这篇关于谁能解释为什么这种排序不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!