-8

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, 4], ['c', 3, 6]]

How can I do that?

1
  • 9
    you can do anything. What have you tried ? Commented Sep 6, 2012 at 11:56

3 Answers 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]]
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this (untested):

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

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.