Python merge lists by common element

前端 未结 6 1631
梦毁少年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 10:09

    Code:

    list1=[('id1','host1'),('id2','host2'),('id1','host5'),('id3','host4'),('id4','host6'),('id5','host8')]
    list1 = map(list,list1)
    list2=[('id1','IP1'),('id2','IP2'),('id3','IP3'),('id4','IP4'),('id5','IP5')]
    list2 = map(list,list2)
    
    for item in list1:
        item += [x[1] for x in list2 if x[0]==item[0]]
    
    list1 += [x for x in list2 if not any(i for i in list1 if x[0]==i[0])]
    
    print list1
    

    Ouptut:

    [['id1', 'host1', 'IP1'], ['id2', 'host2', 'IP2'], ['id1', 'host5', 'IP1'], ['id3', 'host4', 'IP3'], ['id4', 'host6', 'IP4'], ['id5', 'host8', 'IP5']]  
    

    Hope This helps :)

提交回复
热议问题