python两个列表交叉_通过通用标识符对Python中的两个列表进行交叉标识(重叠)...

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 ?

解决方案>>> 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来分别回答你的两个问题。 1. 两个列表对比 如果你想要比较两个列表是否相同,可以直接使用 `==` 运算符进行比较。例如: ```python list1 = [1, 2, 3] list2 = [1, 2, 3] if list1 == list2: print("两个列表相同") else: print("两个列表不同") ``` 上述代码会输出 "两个列表相同"。 如果你想要比较两个列表是否包含相同的元素,可以使用 `set` 函数将列表转换为集合,然后使用 `==` 运算符进行比较。例如: ```python list1 = [1, 2, 3] list2 = [3, 2, 1] if set(list1) == set(list2): print("两个列表包含相同的元素") else: print("两个列表不包含相同的元素") ``` 上述代码同样会输出 "两个列表相同",因为集合的元素是无序的。 2. 两个列表都是路由网段的字符串 如果你想要比较两个列表都是路由网段的字符串,可以使用 Python 的 ipaddress 模块来处理 IP 地址。例如: ```python import ipaddress list1 = ["192.168.0.0/24", "10.0.0.0/8"] list2 = ["10.0.0.0/8", "192.168.1.0/24"] # 将列表的字符串转换为 ipaddress.IPv4Network 对象 networks1 = [ipaddress.IPv4Network(s) for s in list1] networks2 = [ipaddress.IPv4Network(s) for s in list2] # 比较两个列表是否包含相同的网络 if set(networks1) == set(networks2): print("两个列表包含相同的网络") else: print("两个列表不包含相同的网络") ``` 上述代码会输出 "两个列表不包含相同的网络",因为 "192.168.0.0/24" 和 "192.168.1.0/24" 不相同。如果你想要忽略掉 IP 地址的具体值,只比较网络地址和子网掩码,可以使用 `ip_network` 函数代替 `IPv4Network`。例如: ```python networks1 = [ipaddress.ip_network(s) for s in list1] networks2 = [ipaddress.ip_network(s) for s in list2] if set(networks1) == set(networks2): print("两个列表包含相同的网络") else: print("两个列表不包含相同的网络") ``` 上述代码会输出 "两个列表包含相同的网络",因为网络地址和子网掩码相同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值