0

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}]

基本的に、forループから5つの辞書を取得しますが、各辞書を変更せずに、それらすべての辞書を1つのリストに入れることは可能ですか。それらを1つのリストに入れようとするたびに、次のような結果が得られます。

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

http://pastebin.com/60rvcYhb

これは私のプログラムのコピーであり、コードに使用するテキストファイルはありません。基本的に、books.txtには5人の作成者からの5つの異なるtxtファイルが含まれています。これを次のような1つのリストに追加します。

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

1 に答える 1

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}]
于 2012-06-13T09:34:15.490 に答える