我有两个清单:
a= [['A', 'B', 'C', 3], ['P', 'Q', 'R', 4]]
b=[['K',1,1,1,1,1], ['L',1,1,1,1,1], ['M', 1,1,0,1,1], ['J', 0,0,0,0,0], ['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]]
我希望输出如下:
Output=[['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]]
我正在尝试使用a [idx] [0]搜索a中的a。然后我想收集这些项目,并希望像上面的输出。
我的代码如下:
Output=[]
for idx in range(len(Test)):
a_idx = [y[0] for y in b].index(a[idx][0])
a_in_b = b[a_idx]
Output.append(a_in_b[:])
print Output
这不能给我想要的输出。有人可以帮忙吗?
答案 0 :(得分:9)
首先,将b
转换为字典:
b=[['K',1,1,1,1,1], ['L',1,1,1,1,1], ['M', 1,1,0,1,1], ['J', 0,0,0,0,0], ['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]
d = dict((i[0], i[1:]) for i in b)
# d is now:
{'A': [0, 0, 0, 1, 1],
'J': [0, 0, 0, 0, 0],
'K': [1, 1, 1, 1, 1],
'L': [1, 1, 1, 1, 1],
'M': [1, 1, 0, 1, 1],
'P': [0, 1, 0, 1, 1]}
然后将d
映射到a
:
Output = [ i[:1] + d[i[0]] for i in a]
# Output is now: [['A', 0, 0, 0, 1, 1], ['P', 0, 1, 0, 1, 1]]
答案 1 :(得分:1)
虽然eumiro的答案更好,但您要求使用索引的版本。我的版本似乎始终如一:
a= [['A', 'B', 'C', 3], ['P', 'Q', 'R', 4]]
b=[['K',1,1,1,1,1], ['L',1,1,1,1,1], ['M', 1,1,0,1,1], ['J', 0,0,0,0,0], ['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]]
src = [y[0] for y in b]; # I moved this out here so that it is only calculated once
Output = []
for i in range(len(a)): # You have Test here instead??? Not sure why
ai = src.index( a[ i ][ 0 ] )
Output.append( b[ ai ][:] )