2012-07-23 35 views
2

字符串列表可能重複:
How do I sort a list of strings in Python?
How do I sort unicode strings alphabetically in Python?排序在Python

我有一個字符串list的列表,並希望按字母順序排序。當我撥打list.sort()時,列表的第一部分包含以大寫字母按字母順序排列的條目,第二部分包含以小寫字母開頭的排序條目。像這樣:

Airplane 
Boat 
Car 
Dog 
apple 
bicycle 
cow 
doctor 

我用Google搜索了一個答案,但沒有找到一個工作算法。我閱讀了locale模塊和sort參數cmpkey。經常有這lambdasort連續,這使我不能理解的事情。

我怎樣才能得到:

list = ['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat', 'apple', 'Airplane'] 

到:外語

Airplane 
apple 
bicycle 
Boat 
Car 
cow 
doctor 
Dog 

字符,應考慮(如A,E,I)。

+2

你** **肯定你想要的輸出? 「狗」似乎在這個列表中錯誤的地方。 – ThiefMaster 2012-07-23 20:38:13

+0

@ecatmur這不是一個重複的問題,這個比unicode更不區分大小寫 – 2012-07-23 20:40:12

+0

@ThiefMaster:謝謝,我糾正了它。 – rynd 2012-07-23 20:43:25

回答

10

使用區分大小寫的比較:

>>> sorted(['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat', 
     'apple', 'Airplane'], key=str.lower) 
['Airplane', 'apple', 'bicycle', 'Boat', 'Car', 'cow', 'doctor', 'Dog'] 

這實際上是這樣建議的python wiki about sorting

與Python 2.4,兩者list.sort()和排序開始()添加密鑰 參數以指定在進行比較之前在每個列表元素 上調用的函數。

例如,這裏有一個不區分大小寫字符串比較:

>>> sorted("This is a test string from Andrew".split(), key=str.lower) 
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] 
+0

擊敗了我。 – Wug 2012-07-23 20:37:23

+0

這是在'Bor'之後放置'Bär'。 – rynd 2012-07-23 20:51:10

4

似乎是話題在這裏的一個很好的概述: http://wiki.python.org/moin/HowTo/Sorting/

向下滾動頁面的相關這裏;

例如,這裏有一個不區分大小寫字符串比較:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)