我有两个清单:
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 ]]
Run Code Online (Sandbox Code Playgroud)
我希望输出像:
Output=[['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]]
Run Code Online (Sandbox Code Playgroud)
我试图使用a [idx] [0]搜索b中的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
Run Code Online (Sandbox Code Playgroud)
这不会给我想要的输出.有人可以帮忙吗?
首先,转换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]}
Run Code Online (Sandbox Code Playgroud)
然后映射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]]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
68 次 |
最近记录: |