[英]Adding for loops to dictionaries
我在将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个字典,是否有可能将所有这些字典放入一个列表,而无需更改每个字典。 每当我尝试将它们放入一个列表中时,它只会给我一些类似的信息:
[{{'red':4,'blue':3}]
[{'yellow':2,'white':1}]
[{etc.}]
这是我的程序的副本,没有文本文件可用于编码,基本上books.txt仅包含来自5位作者的5个不同的txt文件,而在即时消息中,我在单独的词典中拥有所有这些词的计数我想将其添加到一个列表中,例如:
[{'red':4,'blue':3},{'yellow':2,'white':1}]
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}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.