[{('white', 'man'): 114},
{('white', 'woman'): 91},
{('red', 'man'): 114},
{('red', 'woman'): 114},
{('blu', 'man'): 114},
{('blu', 'woman'): 114}]
对于这个dicts列表,我需要计算dict.keys
的项目,即n
。发生[k, kk for k, kk in dict.keys()]
。
因此,在示例中,结果将如下所示:white = 2
,man = 3
,red = 2
,woman = 3
,blu = 2
。
我尝试了[len(k), len(kk) for k, kk in dict.keys())]
,但它给出了单词的长度,而不是它的数量。
有人可以帮忙吗?
答案 0 :(得分:2)
您可以使用collections.Counter
:
from collections import Counter
msgs = [{('white', 'man'): 114}, {('white', 'woman'): 91}, {('red', 'man'): 114}, {('red', 'woman'): 114}, {('blu', 'man'): 114}, {('blu', 'woman'): 114}]
Counter(word for msg in msgs for words in msg for word in words)
返回
Counter({'woman': 3, 'man': 3, 'blu': 2, 'white': 2, 'red': 2})
你可以读作dict
答案 1 :(得分:0)
这样的事情怎么样?
dictionaries = [{('white', 'man'): 114},
{('white', 'woman'): 91},
{('red', 'man'): 114},
{('red', 'woman'): 114},
{('blu', 'man'): 114},
{('blu', 'woman'): 114}]
借助功能;
def find_key_count(key, lst):
return sum([dic.keys()[0].count(key) for dic in lst])
print find_key_count("white", dictionaries)
返回
2
如果你有一个单独的数据,就不需要把字典作为参数;
def find_key_count(key):
return sum([dic.keys()[0].count(key) for dic in dictionaries])
print find_key_count("man")
打印
3