比较两个列表之间的唯一字符串值并获取 python 中匹配值的计数

Compare unique string values between two lists and get the count of matched values in python

我有两个列表,有些项目是相同的,有些则不是。我想比较两个列表并获取匹配的项目数。

list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']

请教如何在python

中做到这一点

使用Counters和字典理解。

list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
c1 = Counter(list1)
c2 = Counter(list2)
matching = {k: c1[k]+c2[k] for k in c1.keys() if k in c2}
print(matching)
print('{} items were in both lists'.format(len(macthing))

输出:

{'avocado': 2, 'orange': 2, 'tomato': 2, 'mango': 2, 'kiwi': 2}
5 items were in both lists

我想你可以在理解中使用 set.intersection 像这个例子:

list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']

result = {elm: list1.count(elm) + list2.count(elm) for elm in set.intersection(set(list1), set(list2))}

输出:

{'kiwi': 2, 'avocado': 2, 'orange': 2, 'tomato': 2, 'mango': 2}