假设我有两个列表list1
和list2
,如下:
list1 = [ 3, 4, 7 ]
list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]
我想要找到list1
中与list2
中相同的元素数量。
期望输出为4,因为list1
中的3和4在list2
中各出现了两次。因此,总数为4。
假设我有两个列表list1
和list2
,如下:
list1 = [ 3, 4, 7 ]
list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]
我想要找到list1
中与list2
中相同的元素数量。
期望输出为4,因为list1
中的3和4在list2
中各出现了两次。因此,总数为4。
使用列表推导式并检查元素是否存在
c = len([i for i in list2 if i in list1 ])
更好的一个来自@Jon,即
c = sum(el in list1 for el in list2)
输出:4
sum(...)
结合生成器表达式来实现此操作,示例代码如下:>>> list1 = [ 3, 4, 7 ]
>>> list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]
# v returns `True`/`False` and Python considers Boolean value as `0`/`1`
>>> sum(x in list1 for x in list2)
4
__contains__
魔法函数来检查列表中是否存在元素,并使用filter(..)
来过滤掉不符合"in"条件的元素。例如:>>> len(list(filter(list1.__contains__, list2)))
4
# Here "filter(list(list1.__contains__, list2))" will return the
# list as: [3, 3, 4, 4]
想要了解__contains__
的更多细节,请参考:What does __contains__
do, what can call __contains__
function?。
count
方法遍历 first
列表并将给定数字的 出现次数 添加到 sum
中。for number in list1:
s += list2.count(number);
您可以在这里使用collections.Counter,因此首先是一个天真而相当丑陋的实现(我的)。
list1 = [ 3, 4, 7 ]
list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]
from collections import Counter
total = 0
c = Counter(list2)
for i in list1:
if c[i]:
total += c[i]
counter = Counter(list2)
occurrences = sum(counter[v] for v in set(list1))
sum(el in list1 for el in list2)
。 - Jon Clements