-8

我有两个清单:

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

我想只保留字母的共同元素并将两个列表组合成:

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

我怎样才能做到这一点?

4

3 回答 3

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]]
于 2012-09-06T12:14:37.537 回答
1

像这样的东西(未经测试):

Z=[]
for x1, x2 in x:
    for y1, y2 in y:
        if x1 == y1:
            z.append([x1, x2, y2])
于 2012-09-06T12:10:15.113 回答
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]
于 2012-09-06T14:33:34.410 回答