简体   繁体   中英

merge two lists into one multidimensional list in python

I would like to merge these two lists in python

a = [(Test,Name),(D1,value1),(D2,value2),(D3,Value3)]

b = [(D1,value-n1),(D2,value-n2),(D2,value-n3)]

to the new list

new_list = [(Test,Name),(D1,value1,value-n1),(D2,value2,value-n2),(D3,Value3,value-n3)]

I am able to merge them with the zip() but the values are getting added to the first element which i don't want.

This approach will assume that there are no duplicate first elements in tuples inside the same original list.

a = [("Test","Name"),("D1","value1"),("D2","value2"),("D3","Value3")]
b = [("D1","value-n1"),("D2","value-n2"),("D2","value-n3")]

b_lookup = {t[0]: t[1:] for t in b}
c = []

for tup in a:
    if tup[0] in b_lookup:
        c.append(tup + b_lookup.pop(tup[0]))  # also removes element from b_lookup
    else:
        c.append(tup)

print(c)

Output:

[('Test', 'Name'), ('D1', 'value1', 'value-n1'), ('D2', 'value2', 'value-n3'), ('D3', 'Value3')]

使用zip + list comprehension

a[:1] + [(w, x, z) for ((w, x), (y, z)) in zip(a[1:], b)]

It sounds like you want to merge two lists of tuples, where the first item in each tuple is a key, combining tuples when keys match.

If you don't care about the sorting of the outcome:

from collections import defaultdict
>>> c = defaultdict(list)
>>> a = [('Test','Name'),('D1','value1'),('D2','value2'),('D3','Value3')]
>>> b = [('D1','value-n1'),('D2','value-n2'),('D3','value-n3')]
>>> for k, v in a: c[k].append(v)
...
>>> for k, v in b: c[k].append(v)
...
>>> new_list = list(c.iteritems())
>>> new_list
[('Test', ['Name']),
 ('D2', ['value2', 'value-n2']),
 ('D3', ['Value3', 'value-n3']),
 ('D1', ['value1', 'value-n1'])]
from collections import OrderedDict

a = [("Test","Name"),("D1","value1"),("D2","value2"),("D3","Value3")]
b = [("D1","value-n1"),("D2","value-n2"),("D3","value-n3")]

merged = OrderedDict()

for list_ in a, b:
    # default dict like
    for k, v in list_:
        try:
            merged[k].append(v)
        except:
            merged[k] = [v]
# merge the keys and values (list)
merged_list = [(k,) + tuple(v) for k, v in merged.items()]
print(merged_list)
# [('Test', 'Name'), ('D1', 'value1', 'value-n1'), ('D2', 'value2', 'value-n2'), ('D3', 'Value3', 'value-n3')]

例子

>>> a = [("a",1),("b",2)]
>>> b = [("c",3),("b",4)]
>>> c = a+b
>>> c
[('a', 1), ('b', 2), ('c', 3), ('b', 4)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM