简体   繁体   English

Python Sort()方法

[英]Python Sort() method

I am starting to learn Python. 我开始学习Python了。

Can someone explain why sort() returns None? 有人能解释为什么sort()返回None吗?

alist.sort()            ## correct
alist = blist.sort()    ## NO incorrect, sort() returns None

Why shouldn't 为什么不呢

alist = blist.sort()

return the sorted list and give it back to alist? 返回已排序的列表并将其返回给alist? This does not make sense to me. 这对我来说没有意义。

Thanks. 谢谢。

alist.sort() sorts alist in-place, modifying alist itself. alist.sort() alist进行排序,修改alist本身。

If you want a new list to assign somewhere, use blist = sorted(alist) 如果要在某处分配新列表,请使用blist = sorted(alist)

Answering to his question, it returns none because the method always returns None. 回答他的问题,它返回none,因为该方法总是返回None。 When you use it, it automatically modifies the list, so it does not keep the original intact (ie it does not return a sorted copy of the list). 当您使用它时,它会自动修改列表,因此它不会保持原始原样(即它不会返回列表的排序副本)。

使用以下内容:

alist = sorted(blist)

When you want to perform the sorting on same list then you have to use sort() method of list. 如果要在同一列表上执行排序,则必须使用list的sort()方法。 But If you dont want to change the sequence of original list but you need a sorted copy of the original list then use sorted() inbuilt function. 但是,如果您不想更改原始列表的序列,但需要原始列表的排序副本,则使用sorted()内置函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM