繁体   English   中英

检查一个列表中有多少项目出现在另一个列表中

[英]Check how many items from one list appear in another list

例如,如果我有 2 个列表:

list_1 = ['a', 'A']
list_2 = ['a', 'A', 'A', 'b', 'b', 'b', 'b']

如何计数以查看list_1中的项目出现在list_2中的次数?

所以在这种情况下它应该返回3

list_1 = ['a', 'A']
list_2 = ['a', 'A', 'A', 'b', 'b', 'b', 'b']

found = 0
for x in list_1:
    for y in list_2:
        if x == y:
            found += 1
print(found)

使用集合作为参考的有效 O(n) 方法:

list_1 = ['a', 'A']
list_2 = ['a', 'A', 'A', 'b', 'b', 'b', 'b']

set_1 = set(list_1)

count = 0
for e in list_2:
    if e in set_1:
        counter += 1

Output: 3

一个班轮:

sum([x == y for x in list_1 for y in list_2])

另一种解决方案,在其他情况下可能是有益的,因为 Counter()- object 返回一个包含已汇总元素的字典

from collections import Counter

list_1 = ['a', 'A']
list_2 = ['a', 'A', 'A', 'b', 'b', 'b', 'b']

c = Counter(list_2)
print(sum([c[x] for x in list_1]))

只需对列表使用计数:

print(list_2.count(list_1[0]) + list_2.count(list_1[1]))

或循环:

sum_ = 0
for i in range(len(list_1)):
    sum_ += list_2.count(list_1[i])
print(sum_)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM