【发布时间】:2022-12-03 14:27:14
【问题描述】:
我有 2 个列表,我想看看列表 1 中有多少文本在列表 2 中,但我真的不知道有什么方法可以将它们组合起来,输出未求和,我尝试了 sum 方法,但确实如此它为所有单词计算而不是每个单词。
代码:
l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']
for i in l2:
print(f'{l1.count(i)}: {i}')
输出:
0: hey
1: hi
1: hello
1: hello
我想要的是更像这样的东西:
0: hey
1: hi
2: hello
【问题讨论】:
-
首先创建代码来计算单个单词在列表中出现的次数。一旦有了正确的答案,就可以在此基础上进行构建。
标签: python list for-loop count sum