在循环运行时组合具有相同键的字典?
我有一个函数可以生成句子中单词的频率。 我还有一个句子列表。
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 的解决方案,但是如何在像上面给出的循环中运行时将它们组合在一起?
I have a function that generates the frequency of the words in a sentence.
I also have a list of sentences.
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 gives me a result like:
{'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}
But I want a result like this:
{'this': 2, 'word': 2, 'is': 1, 'used': 1, 'for': 1, 'testing': 2, 'code': 2, 'runs': 1, 'the': 1, 'now': 1}
I've seen solutions that use Counter and dictionary comprehension with Set, but How do I do combine them together while running in a loop like given above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想保留现有代码,请让
findFreq
返回一个字典(而不是打印它)。然后在for
循环的每次迭代中更新一个Counter
。如果您想要更短的解决方案,只需使用
If you want to keep your existing code, let
findFreq
return a dict (instead of printing it). Then update aCounter
in each iteration of thefor
loop.If you want a shorter solution just use