通过通用标识符对Python中的两个列表进行交叉标识(重叠) [英] cross-identification (overlap) of two lists in Python by common identifier

查看:145
本文介绍了通过通用标识符对Python中的两个列表进行交叉标识(重叠)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表对,每个列表对由一个标识符列表和一个值列表组成,其中a和b的长度不同.例如:

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

现在,我需要知道与同一个ID对应的值,而我只需要那些在a和b中具有值的值.对于此示例,我想获取常见ID和相应值的列表:

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 ?

推荐答案

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

这篇关于通过通用标识符对Python中的两个列表进行交叉标识(重叠)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆