python - 在 IDF 的字典列表中计数
问题描述
我有一个表格的字典列表
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:
term = word
counter = count[term]
term = ""
print(counter)
这给了我零。
非常感谢任何提示如何进行!
编辑:我想用它的计数替换有问题的单词,所以对于上面的例子,这将是:list_of_dicts = [{id1: [2, 2, 2...]}, {id1: [2, 2, 2..]},..]
解决方案
我假设列表只包含字典对象,每个字典都可以有一个单词列表。
我不确定,您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)
推荐阅读
- machine-learning - 可以得到 2 个答案的激活函数是什么?
- javascript - 一旦 TouchableOpacity 消失,如何让它出现在我的屏幕底部?
- java - 如何修改JITSI Flutter插件并导入修改后的包?
- python - 为什么评估量化模型的指标中有一些 1、0 和一些 NAN?
- firebase - Firebase - Firestore 查询报告
- excel - 通过 vba 绘制图表时遇到问题
- reactjs - 反应路由器与 AWS S3 上具有长查询参数的路由不匹配
- excel - Excel 复选框值属性在极少数情况下无法设置
- python - 如何修复或清理损坏的 JSON 文件
- java - Recyclerview 中的 Exoplayer 带有图像和视频,如 instagram,但仅停止最后一个视频,其他视频在 android 中回压后仍在播放