python - 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
解决方案
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]
推荐阅读
- linkedin - LinkedIn v2 API 中的 Share 和 Activity 有什么区别
- sql - 计算 Oracle 中的特定重复项
- python - Python For循环覆盖字典
- python-3.x - 旋转框不显示
- c# - 我可以用一些可以在四个字段中设置值的二进制逻辑替换值为 0、1、2 和 3 的开关吗?
- javascript - IE CORS - 即使指定了标头,访问控制允许标头错误
- php - 面临问题:Method Illuminate\Database\Query\Builder::links 不存在
- exception - Xamarin.Forms Plugin.Geofence 给出 System.InvalidCastException:指定的转换无效
- javascript - 在运行时更改 Jquery asPieProgress barcolor
- php - 使用其替换 src班级名称