我有以下形式的词典列表
list_of_dicts = [{id1: [word1, word2, word3...]},
{id1: [word1, word2, word3..]},..]
我想在整个列表中而不只是一个值列表中计算单词出现的次数。我很困惑应该使用哪种for循环结构。
我已经尝试过:
from collections import Counter
count = Counter()
term = ""
for dict in list_of_dicts:
for key, val in dict.items():
for word in val:
search_term = word
counter = count[term]
term = ""
print(counter)
这给了我零。
非常感谢任何提示如何进行!
我不确定,通过执行counter = count(term)
会获得什么效果,而通过设置search_term
刚好达到此效果。似乎缺少一些东西。
无论如何,我已经尝试过了,并且可以。
list_of_dicts = [{'id1':['ayush', 'mishra', 'lol']}, {'id2':['ayush', 'mishra2', 'lol']}, {'id3':['ayush2', 'mishra3', 'lol']}]
cnt = 0
target_term = "mishra"
for dict in list_of_dicts:
for key, val in dict.items():
for word in val:
if word == target_term:
cnt+=1
print(cnt)