首页 > 解决方案 > How to find common elements at the same indices in two lists

问题描述

I have two lists and I want to get the elements that are in both lists and at the same indices. For example:

l1 = [1,2,4,7,0,6]
l2 = [1,6,9,7,5]

I want:[1,7]

My attempt:

l3 = []
for i in range(len(l1)):
    if l1[i] == l2[i]:
        l3.append(l1[i])
print(l3)

produces an error:

Traceback (most recent call last):
  File "C:\Users\d-ss\Desktop\t1.py", line 5, in <module>
    if l1[i] == l2[i]:
IndexError: list index out of range

标签: python

解决方案


You can use zip() to zip the two lists so you can iterate through them simultaneously:

l1 = [1,2,4,7,0,6]
l2 = [1,6,9,7,5]
l3 = []
for i, j in zip(l1, l2):
    if i == j:
        l3.append(i)
print(l3)

Output:

[1, 7]

You can also turn it into a list comprehension:

l3 = [i for i, j in zip(l1, l2) if i==j]

推荐阅读