Python - 列表中匹配元素的计数(包括重复项)
给定 2 个列表,计算两个列表中所有相似的元素,包括重复的。
Input : test_list1 = [3, 5, 6, 7, 2, 3, 5], test_list2 = [5, 5, 3, 9, 8, 5]
Output : 4
Explanation : 3 repeats 2 times, and 5 two times, totalling to 4.
Input : test_list1 = [3, 5, 6], test_list2 = [5, 3, 9]
Output : 2
Explanation : 3 repeats 1 time, and 5 one time, totalling to 2.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在这种情况下,我们在迭代一个列表的同时迭代另一个列表的每个元素,并增加计数器。
Python3
# Python3 code to demonstrate working of
# Count of matching elements among lists [ Including duplicates ]
# Using loop
# initializing lists
test_list1 = [3, 5, 6, 7, 2, 3]
test_list2 = [5, 5, 3, 9, 8]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using loop to iterate each element
res = 0
for ele in test_list1:
if ele in test_list2:
res += 1
# printing result
print("All matching elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Count of matching elements among lists [ Including duplicates ]
# Using sum() + generator expression
# initializing lists
test_list1 = [3, 5, 6, 7, 2, 3]
test_list2 = [5, 5, 3, 9, 8]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using sum to count occurrences
res = sum(ele in test_list1 for ele in test_list2)
# printing result
print("All matching elements : " + str(res))
输出
The original list 1 : [3, 5, 6, 7, 2, 3]
The original list 2 : [5, 5, 3, 9, 8]
All matching elements : 3
方法 #2:使用 sum() + 生成器表达式
上述方法的结合就是用来解决这个问题的。在此,我们使用 sum() 对元素进行计数,生成器表达式执行迭代任务。
Python3
# Python3 code to demonstrate working of
# Count of matching elements among lists [ Including duplicates ]
# Using sum() + generator expression
# initializing lists
test_list1 = [3, 5, 6, 7, 2, 3]
test_list2 = [5, 5, 3, 9, 8]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using sum to count occurrences
res = sum(ele in test_list1 for ele in test_list2)
# printing result
print("All matching elements : " + str(res))
输出
The original list 1 : [3, 5, 6, 7, 2, 3]
The original list 2 : [5, 5, 3, 9, 8]
All matching elements : 3