在python中将两个列表合并为一个多维列表

时间:2016-04-19 12:08:24

标签: python list multidimensional-array merge

我想在python中合并这两个列表

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

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

到新列表

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

我能够将它们与zip()合并,但这些值会被添加到我不想要的第一个元素中。

5 个答案:

答案 0 :(得分:1)

这种方法假设同一原始列表中的元组中没有重复的第一个元素。

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)

输出:

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

答案 1 :(得分:0)

使用zip + list comprehension

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

答案 2 :(得分:0)

听起来你想合并两个元组列表,其中每个元组中的第一项是一个键,当键匹配时组合元组。

如果您不关心结果的分类:

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

答案 3 :(得分:0)

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

答案 4 :(得分:-2)

Example

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