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