例如,如果我有 2 個串列:
list_1 = ['a', 'A']
list_2 = ['a', 'A', 'A', 'b', 'b', 'b', 'b']
我怎樣才能算出這些專案list_1出現了多少次list_2?
所以在這種情況下它應該回傳3。
uj5u.com熱心網友回復:
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)
uj5u.com熱心網友回復:
使用集合作為參考的有效 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
輸出: 3
uj5u.com熱心網友回復:
一個班輪:
sum([x == y for x in list_1 for y in list_2])
uj5u.com熱心網友回復:
另一種解決方案,在其他情況下可能是有益的,因為 Counter()- 物件回傳一個包含已匯總元素的字典
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]))
uj5u.com熱心網友回復:
僅count用于串列:
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_)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407424.html
標籤:
上一篇:如何在顫動中將兩個串列相乘
下一篇:為什么我會得到這種輸出?
