2012-06-13 50 views
0

添加for循環來我在插入的for循環的答案到列表麻煩字典

for i in word_list: 
     if i in word_dict: 
      word_dict[i] +=1 
     else: 
      word_dict[i] = 1 
print word_dict 

有了這個,我得到的字數的字典一樣

{'red':4,'blue':3} 
{'yellow':2,'white':1} 

是否有可能以某種方式添加這些答案像

[{'red':4,'blue':3},{'yellow':2,'white':1}] 

基本上我拿到5個字典從一個for循環列表,是否有可能把所有這些字典合併爲一個列表,而不更改每個字典。每次我試圖把它們變成一個列表,它只是給了我這樣的:

[{{'red':4,'blue':3}] 
[{'yellow':2,'white':1}] 
[{etc.}] 

http://pastebin.com/60rvcYhb

這是我的節目的複製,沒有文本文件,即時通訊使用帶,基本上書的代碼。 TXT只包含5名作者在點5個不同的txt文件,並即時在那裏我有所有的人都在單獨的字典字計數,我要添加到一個列表,如:

[{'red':4,'blue':3},{'yellow':2,'white':1}] 
+0

什麼'這裏word_list'? –

回答

6
word_dict_list = [] 

for word_list in word_lists: 
    word_dict = {} 
    for i in word_list: 
     if i in word_dict: 
      word_dict[i] +=1 
     else: 
      word_dict[i] = 1 
    word_dict_list.append(word_dict) 

或者乾脆:

from collections import Counter 
word_dict_list = [ dict(Counter(word_list)) for word_list in word_lists] 

例如:

from collections import Counter 
word_lists = [['red', 'red', 'blue'], ['yellow', 'yellow', 'white']] 
word_dict_list = [ dict(Counter(word_list)) for word_list in word_lists] 
# word_dict_list == [{'blue': 1, 'red': 2}, {'white': 1, 'yellow': 2}] 
+0

+1雖然你應該把它們作爲'Counter'。我不認爲有必要將它們轉換回來。 – jamylak

+0

+1更好的解決方案 – gauden

+0

看到我的問題是,我的實際字數是段落,當我做第一次測試時,它將每個字典放入他們自己的列表中:[{'red':3,'blue:2} ] [{'yellow':4,'white':5}] – 5593404