列表重叠查找器

时间:2019-05-21 10:17:20

标签: python list

我有两个列表:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

需要找到重叠的元素

我正在做作业。

  if (a[i]==b[i]):
    print(i)```

But I got this error:
IndexError: list index out of range,


I expect result:
1 , 2 , 3 , 5 , 8 , 13

2 个答案:

答案 0 :(得分:3)

您收到此错误是因为一个list比另一个长。要解决此问题,您只需将lists转换为sets以消除重复项,然后使用intersection

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

list(set(a) & set(b))
# >> [1, 2, 3, 5, 8, 13]

答案 1 :(得分:2)

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

print(set(a).intersection(set(b)))
# output {1, 2, 3, 5, 8, 13}

当列表中出现的元素超过1个时

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,2]

from collections import defaultdict

dic=defaultdict(int)
dic2=defaultdict(int)

for i in a:
    dic[i]+=1
for i in b:
    dic2[i]+=1

l=list(set(a) & set(b))

solution = [j for i in l for j in [i]*min(dic[i],dic2[i])]
print(solution)
# output [1, 2, 3, 5, 8, 13]