我有两个列表,我试图在一定条件下将第一个列表中的一个项目与第二个列表中的另一个项目匹配(例如,如果它们在同一位置共享相同的数字)。我编写了我的代码以匹配第一组['A','B','C',4,'D'],并且只打印list2中在同一位置有4的集合。基本上我的输出是:
['A','B','C',4,'D']
[1, 2, 3, 4, 5]
好吧,我无法弄清楚如何只打印匹配
这是我的代码:
list1 = [['A','B','C',4,'D'],['A','B','C',9,'D'],['A','B','C',5,'D'],['A','B','C',6,'D'],['A','B','C',7,'D']]
list2 = [[1,2,3,2,5],[1,2,3,5,5],[1,2,3,3,5],[1,2,3,4,5],[1,2,3,1,5],[1,2,3,2,5]]
for var in list1:
print var
for i in range(0,len(list2)):
for var1 in list2:
if list1[0][3] == list2[i][3]:
print var1
答案 0 :(得分:0)
几乎。我不确定这是否是你想要的,但是下面的代码打印了在数组的第4个位置具有相同编号的所有对:
list1 = [['A','B','C',4,'D'],['A','B','C',9,'D'],['A','B','C',5,'D'],
['A','B','C',6,'D'],['A','B','C',7,'D']]
list2 = [[1,2,3,2,5],[1,2,3,5,5],[1,2,3,3,5],[1,2,3,4,5],[1,2,3,1,5],
[1,2,3,2,5]]
for t in list1:
print t
for b in list2:
if t[3] == b[3]:
print b
输出是:
[' A',' B',' C' 4,' D'] [1,2,3,4,5]
[' A',' B',' C',9,' D'] [' A',' B',' C',&n;' D'] [1,2,3,5,5] [' A',' B',' C',6,' D'] [' A',' B',' C',7,' D']
那是你在找什么?
答案 1 :(得分:0)
如果您使用itertools
from itertools import izip
list1 = [['A','B','C',4,'D'],['A','B','C',9,'D'],['A','B','C',5,'D'],['A','B','C',6,'D'],['A','B','C',7,'D']]
list2 = [[1,2,3,2,5],[1,2,3,5,5],[1,2,3,3,5],[1,2,3,4,5],[1,2,3,1,5],[1,2,3,2,5]]
for item1 in list1:
for item2 in list2:
for i,j in izip(item1, item2):
if i==j:
print i
,您的程序会变得更容易。假设你只需要打印元素
from itertools import izip
list1 = [['A','B','C',4,'D'],['A','B','C',9,'D'],['A','B','C',5,'D'],['A','B','C',6,'D'],['A','B','C',7,'D']]
list2 = [[1,2,3,2,5],[1,2,3,5,5],[1,2,3,3,5],[1,2,3,4,5],[1,2,3,1,5],[1,2,3,2,5]]
for i in izip(list1,list2):
for item1, item2 in izip(i[0],i[1]):
if item1 == item2:
print item1
通过两次使用izip,会更容易
NULLIF()