cross-identification (overlap) of two lists in Python by common identifier

耗尽温柔 提交于 2019-12-11 05:38:33

问题


I have two list pairs, each consisting of a list of identifiers and a list of values, where a and b do not have the same length. For example:

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

Now, I need to know wich values correspond to the same id and I only need those that have values in a and b. For this example, I would like to get a list of the common ids and the corresponding values:

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

What would be the best/quickest way to accomplish that ?


回答1:


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


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



回答3:


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

It's output is :

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


来源:https://stackoverflow.com/questions/17343010/cross-identification-overlap-of-two-lists-in-python-by-common-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!