搜索操作有问题

use*_*592 1 python

我有两个清单:

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)

这不会给我想要的输出.有人可以帮忙吗?

eum*_*iro 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]}
Run Code Online (Sandbox Code Playgroud)

然后映射da:

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)

  • @user:`index`方法在这里效率较低.你为什么要用它? (4认同)