2

Say I have the following two lists/numpy arrays:

List1 = [[1,2,3,4], [10,11,12], ...]
List2 = [[-1,-2-3,-4], [-10,-11,-12], ...]

I would like to obtain a list that holds the zipping of the nested lists above:

Result = [[(1,-1), (2,-2), (3,-3), (4,-4)], [(10,-10), (11, -11), (12,-12)], ...]

Is there a way to do this with a one-liner (and in a Pythonic way)?

1
  • 1
    The following answer supports arbitrarily deep nested lists, not sure whether or not that is a requirement here: stackoverflow.com/a/12630570/505154 Commented Dec 3, 2012 at 0:20

1 Answer 1

7
l1 = [[1,2,3,4], [10,11,12]]
l2 = [[-1,-2,-3,-4], [-10,-11,-12]]

print [zip(a,b) for a,b in zip(l1,l2)]
[[(1, -1), (2, -2), (3, -3), (4, -4)], [(10, -10), (11, -11), (12, -12)]]
Sign up to request clarification or add additional context in comments.

4 Comments

Was just about to hit post on that same answer! gaw! +1. Even with the a,b names.
You could also suggest itertools.izip for the original lists in case they are huge. It would save on creating a big temp zip list. But only if the source lists would be large
@jdi And only in 2.x - in 3.x zip() produces generators, not lists, anyway.
@Lattyware: So far I have only assumed people are using py3 if they tag it or specifically mention it. But good info all the same!

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.