Python通过通用元素合并列表 [英] Python merge lists by common element

查看:310
本文介绍了Python通过通用元素合并列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并两个在它们之间有共同点的列表(在这种情况下,这是一个id参数). 我有这样的东西:

Im trying to merge two lists that have a common thing between them (in that case is a the id parameter). I have something like this:

list1=[(id1,host1),(id2,host2),(id1,host5),(id3,host4),(id4,host6),(id5,host8)]

list2=[(id1,IP1),(id2,IP2),(id3,IP3),(id4,IP4),(id5,IP5)]

主机是唯一的,但是list1中的ID可以重复,如您所见. 我想要一个将id参数与两个列表相关联的输出:

The host is unique but the id in the list1 can be repeated like you can see. I want a output that relates the id parameter that is the common thing to both lists:

一些输出,例如:

IP1(host1,host5), IP2(host2), IP3(host4), IP4(host6), IP5(host8)

如您所见,IP1有两个关联的主机.

As you can see the IP1 has two host associated.

有什么快速的方法吗?

谢谢

推荐答案

>>> from collections import defaultdict
>>> list1 = [('id1','host1'),('id2','host2'),('id1','host5'),('id3','host4'),('id4','host6'),('id5','host8')]
>>> list2 = [('id1','IP1'),('id2','IP2'),('id3','IP3'),('id4','IP4'),('id5','IP5')]
>>> d1 = defaultdict(list)
>>> for k,v in list1:
...     d1[k].append(v)
... 

您可以打印这样的项目

>>> for k, s in list2:
...     print s, d1[k]
... 
IP1 ['host1', 'host5']
IP2 ['host2']
IP3 ['host4']
IP4 ['host6']
IP5 ['host8']

您可以使用列表推导将结果放入列表中

You can use a list comprehension to put the results into a list

>>> res = [(s, d1[k]) for k, s in list2]
>>> res
[('IP1', ['host1', 'host5']), ('IP2', ['host2']), ('IP3', ['host4']), ('IP4', ['host6']), ('IP5', ['host8'])]

这篇关于Python通过通用元素合并列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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