我有两个清单:
x = [['a', 1], ['b', 2], ['c', 3]]
y = [['a', 4], ['c', 6]]
我想只保留字母的共同元素并将两个列表组合成:
[['a', 1, 4], ['c', 3, 6]]
我怎样才能做到这一点?
我有两个清单:
x = [['a', 1], ['b', 2], ['c', 3]]
y = [['a', 4], ['c', 6]]
我想只保留字母的共同元素并将两个列表组合成:
[['a', 1, 4], ['c', 3, 6]]
我怎样才能做到这一点?
>>> 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]]
像这样的东西(未经测试):
Z=[]
for x1, x2 in x:
for y1, y2 in y:
if x1 == y1:
z.append([x1, x2, y2])
对于这类事情,字典通常要好得多。
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]