如何计算一个列表中的单词在另一个列表中出现的次数



我有两个列表,我想看看列表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

我认为一个简单的解决方法就是翻转你在列表中循环的方式:

l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']
for i in l1:
print(f'{l2.count(i)}: {i}')

输出:

2: hello
1: hi

试试这个


from collections import Counter
l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']
c = Counter(l2)

for a in l1:
print(f"{c[a]}: {a}")
c.pop(a)
print(*["0: " + a for a in c.keys()], sep='n')

输出
2: hello
1: hi
0: hey

最新更新