在Python中合并两个嵌套列表

时间:2012-09-06 11:54:23

标签: python list dictionary

我有两个清单:

x = [['a', 1], ['b', 2], ['c', 3]]
y = [['a', 4], ['c', 6]]

我想只保留字母的共同元素,并将2个列表合并为:

[['a', 1, 4], ['c', 3, 6]]

我该怎么做?

3 个答案:

答案 0 :(得分:3)

>>> x = [['a', 1], ['b', 2], ['c', 3]]
>>> y = [['a', 4], ['c', 6]]
>>> lazy = dict
>>> lazyx = lazy(x)
>>> lazyy = lazy(y)
>>> [[lazy, lazyx[lazy], lazyy[lazy]] for lazy in lazyx if lazy in lazyy]
[['a', 1, 4], ['c', 3, 6]]

答案 1 :(得分:1)

像这样(未经测试):

Z=[]
for x1, x2 in x:
    for y1, y2 in y:
        if x1 == y1:
            z.append([x1, x2, y2])

答案 2 :(得分:0)

字典对于这些事情来说通常要好得多。

z = {}
for key, val in x + y:
    z[key] = z.get(key, []) + [val]
print z #{'a': [1, 4], 'c': [3, 6], 'b': [2]}
print a["b"] #[2]
print a["c"] #[3, 6]