![](/img/trans.png)
[英]Python: Find count of elements of one list when condition in another list is fulfilled
[英]Python: Find count of the elements of one list in another list
假设我有两个列表list1
和list2
:
list1 = [ 3, 4, 7 ]
list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]
我想找到list2
中存在的list1
元素的数量。
预期输出为4,因为list1
中的3和4在list2
中出现两次。 因此,总计数为4。
使用列表理解并检查元素是否存在
c = len([i for i in list2 if i in list1 ])
更好的一个来自@Jon ie
c = sum(el in list1 for el in list2)
产量: 4
可以遍历first
列表和add
给定数量的出现次数的sum
使用count
方法。
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]
如果您在第一个列表(HT Jon)中有重复项,则不会考虑会发生什么,而更优雅的版本是:
counter = Counter(list2)
occurrences = sum(counter[v] for v in set(list1))
您可以使用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
作为替代方案,您也可以使用Python的__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__
更多详细信息,请阅读: __contains__
做什么,可以调用__contains__
函数? 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.