python list元素合并,Python通过通用元素合并列表

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

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:

Some output like:

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

As you can see the IP1 has two host associated.

Is there any fast way to do it?

Thank you

解决方案>>> 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)

...

You can print the items like this

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值