創建一個字典來保存所有索引,包括重複的元素,然後用列表比較增加索引的共同元素:
from collections import defaultdict
d = defaultdict(list)
for i, ele in enumerate(A):
d[ele].append(i)
print([ele for i in B for ele in d[i] if i in d])
[6, 6, 1, 4, 5]
如果我們增加了幾個80的,你可以看到它返回所有合適的索引:
A = [0, 20, 40, 60, 80, 80, 100, 80, 120, 80,140, 160, 180, 200, 220, 240, 260, 280, 300, 320, 340,21]
B = [87, 78343, 100, 38, 100, 20, 80]
from collections import defaultdict
d = defaultdict(list)
for i, ele in enumerate(A):
d[ele].append(i)
print([ele for i in B for ele in d[i] if i in d])
[6, 6, 1, 4, 5, 7, 9, 21]
對於大型列表,這將是非常有效的,查找和0(1)
,所以構建字典的成本將抵消任何合理大小的數據和規模。
有一兩件事是清楚的,如果你有兩個列表中重複條目,會發生什麼,例如:
A = [1, 2, 2, 3, 3, 4, 5]
B = [3, 4, 3, 5]
變爲:
[3, 4, 5 3, 4, 6]
其中3,4
因爲3是在重複出現了兩次都。
如果是這樣的話,你可以繼續在B還元素的計數:
from collections import defaultdict, Counter
d = defaultdict(list)
for i, ele in enumerate(A):
d[ele].append(i)
cn = Counter(B)
l = []
for i in B:
if i in d:
val = d[i]
l.extend(val.pop(0) if len(val) > 1 and cn[i] > 1 else ele for ele in val)
print(l)
[3, 5, 4, 6]
不過,如果項目出現B中3次,你會得到一個索引的第一個值最後出現:
A = [1, 2, 2, 3, 3, 4, 5]
B = [3, 4, 3, 5, 3]
[3, 5, 4, 6, 4]
如果一個值在兩個列表中出現多次,該怎麼辦?例如,'[0,1,1,2]'和'[1,1,3,4]'?那應該是'[1,2,2]'嗎? –