[英]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.