2011-05-25 62 views
1

我有兩個列表:問題的搜索操作

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 ]] 

我試圖用一個[IDX] [0搜索A在B ]。然後我想收集這些項目,並希望像上面的輸出。

我的代碼如下所示:

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 

這不會給我所需的輸出。有人可以幫忙嗎?

回答

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 ][:]) 
+0

謝謝,這對我有用。 – user741592 2011-05-25 10:30:49

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]} 

然後映射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]] 
+0

我想使用*索引*方法。任何其他方式使用上述代碼的索引。 – user741592 2011-05-25 08:19:55

+4

@user:'index'方法在這裏效率較低。你爲什麼要使用它? – 2011-05-25 08:20:41

+0

原因是我已經有一個代碼,我在* a *中有單個條目,並且索引方法適用於此。 – user741592 2011-05-25 08:23:41