Merge Two Nested Lists In Python
I have two lists: x = [['a', 1], ['b', 2], ['c', 3]] y = [['a', 4], ['c', 6]] I would like to keep only the common elements of the letters and combine the 2 lists into: [['a', 1,
Solution 1:
>>> 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]]
Solution 2:
Something like this (untested):
Z=[]forx1,x2 in x:fory1,y2 in y:ifx1==y1:z.append([x1,x2,y2])
Solution 3:
A dictionary is generally a lot better for these kinds of things.
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]
Post a Comment for "Merge Two Nested Lists In Python"