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

2024-04-25 01:39:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串列表:

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)

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

print (dic)

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

Tags: 字符串in列表for字典countlevelinternal
3条回答

与在示例输出中创建dict列表不同,您只创建了一个dict(每次检查一个短语时都会覆盖单词)。您可以使用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}]

试试这个

from collections import Counter

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']

result = [{b: dict(Counter(i.split())).get(b, 0) for b in B} for i in A]
print(result)

输出:

[{'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}]

两个问题:您在错误的位置初始化了dic,而没有在列表中收集这些dic。解决方法如下:

C = []    
for i in A:
    dic = {}
    t=i.split()
    for j in B:
        dic[j]=t.count(j)
    C.append(dic)
# Result:
[{'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}]

相关问题 更多 >