像这样的东西可以工作:
l = []
for x,y in zip(a,b):
if x == y:
l.append(x)
就列表理解而言,可以这样写:
l = [x for x,y in zip(a,b) if x == y]
解释
zip(a,b)
将生成以下内容:
>>> zip(a,b)
[(20, 1), (35, 35), (226, 69), (62, 103), (129, 137), (108, 171), (156, 205), (225, 239), (115, 18), (35, 52), (162, 86), (43, 120), (9, 154), (120, 188), (181, 222), (220, 240)]
>>>
然后,您遍历结果的每个元素 (x,y)zip(a,b)
并比较 x 和 y 。
可重现的例子:
>>> a = [20, 35, 226, 62, 129, 108, 156, 225, 115, 35, 162, 43, 9, 120, 181, 220
>>> b = [1, 35, 69, 103, 137, 171, 205, 239, 18, 52, 86, 120, 154, 188, 222, 240
>>> zip(a,b)
[(20, 1), (35, 35), (226, 69), (62, 103), (129, 137), (108, 171), (156, 205), (2
>>> [x for x,y in zip(a,b) if x == y ]
[35]
>>>