2012-02-23 21 views
4

我想執行一個內聯操作,我需要將列表作爲過程的一部分進行排序。 list類型對象的sort函數在所調用的列表上運行,而不是返回結果。是否有返回排序列表的list.sort()版本?

Python docs證實了這一點:

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() 

使用上面的代碼將幫助我減少我的代碼的長度和冗長度。

+0

」似乎在名單上操作「。這是錯誤的。它不「似乎」。它是這樣定義的。沒有例外。這就是它應該工作的方式。 'list.sort()'不返回一個值;它修改了列表。 'result = .... sort()'不能工作。根據定義。 – 2012-02-23 19:40:14

+0

「似乎證實了這一點:」這是錯誤的。他們確實證實了這一點 – 2012-02-23 19:48:47

+0

謝謝,更正。 – 2012-02-23 19:59:29

回答

13

有內置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)) 

如果那是ou你正在尋找的東西。

+4

'sorted(foo)'本質上是'temp = list(foo); temp.sort(); return temp'在技術上不需要將字符串轉換爲列表,然後將它傳遞給'sorted()'。 :-) – kindall 2012-02-23 19:25:44

5

使用sorted

它從可迭代的項目中返回一個新的排序列表。

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

的區別在於,list.sort()方法僅針對列表定義。相比之下,sorted()函數接受任何可迭代的。

所以,你可以做

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

看看這個漂亮的文章Sorting Mini-HOW TO

0

排序是你的朋友在這裏。它不是列表類的成員函數,它是一個將列表作爲參數的內置函數。

班級列表沒有排序功能。 「

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

>> [1, 2, 4, 5] 
相關問題