python - 谁能解释为什么这种排序不起作用?

标签 python sorting

例如,如果我有这样一个列表:

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 应该仅在您不想影响原始列表并且想将该列表的排序版本分配给其他变量时使用。

除了列表之外,其他数据结构如settuplesdicts等没有它们自己的.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/

相关文章:

python - 按两列将值映射到 DataFrame 上

python - 避免日志记录模块中的单例模式

python - 对如何在 python 中将代码编写为函数感到困惑

java - 在java中对元组列表进行排序的有效方法

java - 使用预定义的索引列表对 ArrayList 进行排序

python - 企业 Gmail 中的 IMAP

python - 如何通过 Python 使用 Azure 诊断?

php - 如何按点对这个多维数组进行排序?

java - 在 Java 中操作数据时的良好实践

PHP/MySQL : how to display the words before and after the searched item