繁体   English   中英

是否有list.sort()版本返回排序列表?

[英]Is there a version of list.sort() that returns the sorted list?

我正在尝试执行内联操作,我需要将列表排序为进程的一部分。 list类型对象的sort功能在调用它的列表上运行,而不是返回结果。

Python文档证实了这一点:

list.sort()
对列表中的项目进行排序。

我通过Python命令行尝试了这个,结果如下:

>>> a = list("hello").sort()
>>> print a
None
>>> b = list("hello")
>>> print b
['h', 'e', 'l', 'l', 'o']
>>> b.sort()
>>> print b
['e', 'h', 'l', 'l', 'o']

有没有办法绕过这个问题,并建立一个如下所示的行?

result = list(random.choice(basesalts)).sort()

使用上面的代码可以帮助我减少代码的长度和冗长。

有内置的sorted()

>>> a = sorted(list('hello'))
>>> a
['e', 'h', 'l', 'l', 'o']

另请注意,您不再需要list()

>>> sorted('hello')
['e', 'h', 'l', 'l', 'o']

由于basesalts似乎是一个字符串列表,你可以这样做:

result = sorted(random.choice(basesalts))

如果这是你正在寻找的那种输出。

使用排序

它从iterable中的项返回一个新的排序列表。

>>> a = sorted(list('hello'))
>>> a
['e', 'h', 'l', 'l', 'o']
>>>

不同之处在于list.sort()方法仅为列表定义。 相反,sorted()函数接受任何iterable。

所以,你可以做到

>>> a = sorted('hello')
>>> a
['e', 'h', 'l', 'l', 'o']
>>>

看看这篇精彩的文章Sorting Mini-HOW TO

排序是你的朋友。 它不是列表类的成员函数,它是一个内置函数,它将列表作为参数。

类列表没有排序功能。

list1 = [ 1, 4, 5, 2]
print sorted(list1)

>> [1, 2, 4, 5]

暂无
暂无

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

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