Python merge lists by common element

前端 未结 6 1519
梦毁少年i
梦毁少年i 2021-01-26 09:24

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

6条回答
  •  暖寄归人
    2021-01-26 09:50

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

提交回复
热议问题