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

Gab*_*lli 4 python sorting random shuffle list

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

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']
Run Code Online (Sandbox Code Playgroud)

有没有办法绕过这个问题,并使下面的行成为可能?

result = list(random.choice(basesalts)).sort()
Run Code Online (Sandbox Code Playgroud)

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

Rik*_*ggi 13

有内置的sorted():

>>> a = sorted(list('hello'))
>>> a
['e', 'h', 'l', 'l', 'o']
Run Code Online (Sandbox Code Playgroud)

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

>>> sorted('hello')
['e', 'h', 'l', 'l', 'o']
Run Code Online (Sandbox Code Playgroud)

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

result = sorted(random.choice(basesalts))
Run Code Online (Sandbox Code Playgroud)

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

  • `sorted(foo)`本质上是`temp = list(foo); temp.sort(); 返回temp`技术上不需要在将字符串传递给`sorted()`之前将其转换为列表.:-) (4认同)

Ran*_*Rag 5

使用排序.

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

>>> a = sorted(list('hello'))
>>> a
['e', 'h', 'l', 'l', 'o']
>>>
Run Code Online (Sandbox Code Playgroud)

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

所以,你可以做到

>>> a = sorted('hello')
>>> a
['e', 'h', 'l', 'l', 'o']
>>>
Run Code Online (Sandbox Code Playgroud)

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