我正在尝试执行内联操作,我需要将列表排序作为流程的一部分。
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/