2013-06-27 80 views
1

我有兩個列表對,每個列表對包含標識符列表和值列表,其中a和b的長度不相同。例如:Python中兩個列表的交叉標識(重疊)通過公共標識符

a_id = [1, 2, 4, 5, 9, 12, 13] 
a_val = [13., 32., 5., 9., 32., 4., 8.] 
b_id = [1, 3, 4, 6, 9] 
b_val = [12., 27., 1., 3., 19.] 

現在,我需要知道哪些值對應於相同的ID,我只需要在a和b中具有值的那些值。對於這個例子,我想獲得共同的ID和相應值的列表:

common_id = [1, 4, 9] 
common_a_val = [13., 5., 32.] 
common_b_val = [12., 1., 19.] 

會是什麼來實現這一目標的最佳/最快的方法是什麼?

回答

2
>>> common_id = [i for i in a_id if i in b_id] 
>>> common_id 
[1, 4, 9] 
>>> common_a_val = [a_val[a_id.index(i)] for i in common_id] 
>>> common_a_val 
[13.0, 5.0, 32.0] 
>>> common_b_val = [b_val[b_id.index(i)] for i in common_id] 
>>> common_b_val 
[12.0, 1.0, 19.0] 
+0

這是太容易了,我只是看不到它;)謝謝! – frixhax

+0

很高興它能幫助你! – Emmanuel

3
>>> a_d = dict(zip(a_id,a_val)) 
>>> b_d = dict(zip(b_id,b_val)) 
>>> common_ids = a_d.viewkeys() & b_d.viewkeys() 
set([1, 4, 9]) 
>>> common_a_val = [a_d[key] for key in common_ids] 
[13.0, 5.0, 32.0] 
>>> common_b_val = [b_d[key] for key in common_ids] 
[12.0, 1.0, 19.0] 
0
def common_elements(list1, list2): 
    return [element for element in list1 if element in list2] 
a_id = [1, 2, 4, 5, 9, 12, 13] 
a_val = [13., 32., 5., 9., 32., 4., 8.] 
b_id = [1, 3, 4, 6, 9] 
b_val = [12., 27., 1., 3., 19.] 
common_a_val=[];common_b_val=[] 
common_id=common_elements(a_id,b_id) 
for i in common_id: 
    common_a_val.append(a_val[a_id.index(i)]) 
    common_b_val.append(b_val[b_id.index(i)]) 
print common_id,common_a_val,common_b_val 

它的輸出是:

[1, 4, 9] [13.0, 5.0, 32.0] [12.0, 1.0, 19.0]