在循环中 运行 时将具有相同键的字典组合在一起?

Combining dictionaries with same key while running in a loop?

我有一个函数可以生成句子中单词的出现频率。 我还有一个句子列表。

sentences = ["this word is used for testing", "code runs this word", "testing the code now"]

def findFreq():
    # create new dict
    # word freq finding code
    # print dict


for sen in sentences:
    findFreq(sen)

这给了我这样的结果:

{'this': 1, 'word': 1, 'is': 1, 'used': 1, 'for': 1, 'testing': 1}
{'code': 1, 'runs': 1, 'this': 1, 'word': 1}
{'testing': 1, 'the': 1, 'code': 1, 'now': 1}

但我想要这样的结果:

{'this': 2, 'word': 2, 'is': 1, 'used': 1, 'for': 1, 'testing': 2, 'code': 2, 'runs': 1, 'the': 1, 'now': 1}

我见过将计数器和字典理解与 Set 结合使用的解决方案,但是如何在 运行 中将它们组合在一起,就像上面给出的循环一样?

如果你想保留你现有的代码,让 findFreq return 一个字典(而不是打印它)。然后在for循环的每次迭代中更新一个Counter

from collections import Counter

c = Counter()
for sen in sentences:
    c.update(findFreq(sen))

print(c)

如果您想要更短的解决方案,只需使用

>>> Counter(' '.join(sentences).split())
Counter({'this': 2,
         'word': 2,
         'is': 1,
         'used': 1,
         'for': 1,
         'testing': 2,
         'code': 2,
         'runs': 1,
         'the': 1,
         'now': 1})