Python merge lists by common element

前端 未结 6 1515
梦毁少年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:12

    Maybe something like this?

    #!/usr/local/cpython-3.3/bin/python
    
    import pprint
    import collections
    
    class Host_data:
        def __init__(self, ip_address, hostnames):
            self.ip_address = ip_address
            self.hostnames = hostnames
            pass
    
        def __str__(self):
            return '{}({})'.format(self.ip_address, ','.join(self.hostnames))
    
        __repr__ = __str__
    
        # The python 2.x way
        def __cmp__(self, other):
            if self.ip_address < other.ip_address:
                return -1
            elif self.ip_address > other.ip_address:
                return 1
            else:
                if self.hostnames < other.hostnames:
                    return -1
                elif self.hostnames > other.hostnames:
                    return 1
                else:
                    return 0
    
        # The python 3.x way
        def __lt__(self, other):
            if self.__cmp__(other) < 0:
                return True
            else:
                return False
    
    
    def main():
        list1=[('id1','host1'),('id2','host2'),('id1','host5'),('id3','host4'),('id4','host6'),('id5','host8')]
    
        list2=[('id1','IP1'),('id2','IP2'),('id3','IP3'),('id4','IP4'),('id5','IP5')]
    
        keys1 = set(tuple_[0] for tuple_ in list1)
        keys2 = set(tuple_[0] for tuple_ in list2)
        keys = keys1 | keys2
    
        dict1 = collections.defaultdict(list)
        dict2 = {}
    
        for tuple_ in list1:
            id_str = tuple_[0]
            hostname = tuple_[1]
            dict1[id_str].append(hostname)
    
        for tuple_ in list2:
            id_str = tuple_[0]
            ip_address = tuple_[1]
            dict2[id_str] = ip_address
    
        result_dict = {}
        for key in keys:
            hostnames = []
            ip_address = ''
            if key in dict1:
                hostnames = dict1[key]
            if key in dict2:
                ip_address = dict2[key]
            host_data = Host_data(ip_address, hostnames)
            result_dict[key] = host_data
    
        pprint.pprint(result_dict)
        print('actual output:')
        values = list(result_dict.values())
        values.sort()
        print(', '.join(str(value) for value in values))
    
        print('desired output:')
        print('IP1(host1,host5), IP2(host2), IP3(host4), IP4(host6), IP5(host8)')
    
    
    main()
    

提交回复
热议问题