通过公共标识符在Python中交叉标识(重叠)两个列表

时间:2013-06-27 12:21:03

标签: python list match overlap

我有两个列表对,每个列表对包含一个标识符列表和一个值列表,其中a和b的长度不同。例如:

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

实现这一目标的最佳/最快方法是什么?

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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]

答案 2 :(得分: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]