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

标签 python list sorting random shuffle

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

Python docs证实这一点:

list.sort()
Sort the items of the list, in place.

我通过 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))

如果这是您正在寻找的输出类型。

关于python - 是否有返回排序列表的 list.sort() 版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9419689/

相关文章:

python - PyParsing 不同的字符串长度

javascript - 无法以正确的方式在无序列表中显示 xml 元素的内容

node.js - 如何实现 RESTful API 的查询字符串参数

javascript - 在 Windows Javascript 应用程序中未获得正确排序的数组

algorithm - "constant factor of N"的含义?

python - 输出相同时不覆盖文件的简单方法

python - 如何找到 Seaborn 版本

python - IPython - 在导入的文件中设置断点

将列表复制到二进制文件

javascript - 仅在选中复选框时显示列表