python - 字典只返回 for 循环中的最后一个键值对

标签 python python-3.x list dictionary

我有一个字符串列表:

A = [
    'philadelphia court excessive disappointed court hope hope',
    'hope hope jurisdiction obscures acquittal court',
    'mention hope maryland signal held mention problem internal reform life bolster level grievance'
    ]

另一个列表是:

B = ['court', 'hope', 'mention', 'life', 'bolster', 'internal', 'level']

我想根据字符串列表 A 中列表词 B 的出现次数创建字典。类似的东西,

C = [
        {'count':2,'hope':2,'mention':0,'life':0,'bolster':0,'internal':0,'level':0},
        {'count':1,'hope':2,'mention':0,'life':0,'bolster':0,'internal':0,'level':0},
        {'count':0,'hope':1,'mention':2,'life':1,'bolster':1,'internal':1,'level':1}
    ]

我喜欢的,

dic={}
for i in A:
    t=i.split()
    for j in B:
        dic[j]=t.count(j)

但是,它只返回最后一对字典,

打印(dic)

{'court': 0,
 'hope': 1,
 'mention': 2,
 'life': 1,
 'bolster': 1,
 'internal': 1,
 'level': 1}

最佳答案

与在示例输出中创建字典列表不同,您只创建了一个字典(并在每次检查短语时覆盖字数)。您可以使用 re.findall 来计算每个短语中的单词出现次数(如果您的任何短语包含单词后跟标点符号(例如“hope?”),这样做的好处是不会失败)。

import re

words = ['court', 'hope', 'mention', 'life', 'bolster', 'internal', 'level']
phrases = ['philadelphia court excessive disappointed court hope hope','hope hope jurisdiction obscures acquittal court','mention hope maryland signal held mention problem internal reform life bolster level grievance']

counts = [{w: len(re.findall(r'\b{}\b'.format(w), p)) for w in words} for p in phrases]

print(counts)
# [{'court': 2, 'hope': 2, 'mention': 0, 'life': 0, 'bolster': 0, 'internal': 0, 'level': 0}, {'court': 1, 'hope': 2, 'mention': 0, 'life': 0, 'bolster': 0, 'internal': 0, 'level': 0}, {'court': 0, 'hope': 1, 'mention': 2, 'life': 1, 'bolster': 1, 'internal': 1, 'level': 1}]

关于python - 字典只返回 for 循环中的最后一个键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976224/

相关文章:

python - 从 Mac Os X 全局路径中删除已安装的 Python 3.5

python - UnicodeEncodeError : 'ascii' codec can't encode character u'\xc7' in position 0: when writting to . CSV

python-3.x - Gtk.CssProvider.load_from_data TypeError : Item 0: Must be number, not str

python - 使用一个完全训练的文件和另一个完全测试的文件进行分类

JAVA - 如何通过比较列表中的多个值来使用比较器对对象列表进行排序

C# List of List 的最后一个元素

python - Dockerfile 努力安装 Python Geopandas 模块

python - 尝试使用统计库计算大数据集的 mode() 时出现统计错误

linux - 设置 'correct' pip3

Python 设置查找效率