2013-06-28 69 views
4

Im在某個問題上停滯不前,我一直都在這個問題上一直圍繞,直到我迷惑自己。Python:基於單詞的第一個字符的分割列表

我所試圖做的是採取的單詞列表:

['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'Biblical', 'Bill', 'Billgone'] 

然後對它們進行排序,並根據字母順序:

A 
About 
Absolutely 
After 

B 
Bedlam 
Behind 

等等

是存在的,簡單的方法來做到這一點?

回答

8

通過特定的按鍵,比如第一個字母使用itertools.groupby()將你輸入:

from itertools import groupby 
from operator import itemgetter 

for letter, words in groupby(sorted(somelist), key=itemgetter(0)): 
    print letter 
    for word in words: 
     print word 
    print 

如果列表已經排序,則可以省略sorted()電話。可回叫的itemgetter(0)將返回每個單詞的第一個字母(索引0處的字符),然後groupby()將產生該密鑰加上一個只包含那些密鑰保持不變的項目的迭代。在這種情況下,這意味着循環使用words會爲您提供以相同字符開頭的所有項目。

演示:

>>> somelist = ['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'Biblical', 'Bill', 'Billgone'] 
>>> from itertools import groupby 
>>> from operator import itemgetter 
>>> 
>>> for letter, words in groupby(sorted(somelist), key=itemgetter(0)): 
...  print letter 
...  for word in words: 
...   print word 
...  print 
... 
A 
About 
Absolutely 
After 
Aint 
Alabama 
AlabamaBill 
All 
Also 
Amos 
And 
Anyhow 
Are 
As 
At 
Aunt 
Aw 

B 
Bedlam 
Behind 
Besides 
Biblical 
Bill 
Billgone