2011-06-01 72 views
1

我該如何排序?Python排序字​​符串列表

>>> list = ["a_0","a_1","a_2","a_3","a_10","a_11","a_23","a_5","a_6","a_5"] 
>>> sorted(list) 
['a_0', 'a_1', 'a_10', 'a_11', 'a_2', 'a_23', 'a_3', 'a_5', 'a_5', 'a_6']> 

我需要它是:

['a_0', 'a_1', 'a_2', 'a_3', 'a_5', 'a_5', 'a_6, 'a_10', 'a_11', 'a_23']> 

因此,它基於「數字」分類 感謝我前進!

回答

10

您的意思是:sorted(list, key=lambda d: int(d[2:]))

+0

那就是它!非常感謝 – Harry 2011-06-01 09:22:52

+2

請注意,這將根據數字對* only *進行排序,而不是對'a'進行排序。它還要求數字以字符2開始。 – 2011-06-01 09:25:05

+0

「請注意,這將僅根據數字進行排序」,實際上是 – taijirobot2 2011-06-01 09:39:28

6

您需要編寫一個「鍵功能」,將您的字符串轉換爲具有所需順序的搜索鍵。例如:

def key(k): 
    s, sep, i = k.partition('_') 
    return (s, int(i)) 

>>> L = ["a_0","a_1","b_2","c_2","a_10","a_11","a_23","b_5","a_6","c_5"] 
>>> sorted(L, key=key) 
['a_0', 'a_1', 'a_6', 'a_10', 'a_11', 'a_23', 'b_2', 'b_5', 'c_2', 'c_5'] 
+0

謝謝,這實際上是我的確切目的所需要的。我改變了一下,現在完美。雖然你的回答是正確的,但我已經根據問題在正確的答案上標記了答案。 – Harry 2011-06-01 09:46:51