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)?

Amelio Vazquez-Reina
  • 91,494
  • 132
  • 359
  • 564
  • 1
    The following answer supports arbitrarily deep nested lists, not sure whether or not that is a requirement here: http://stackoverflow.com/a/12630570/505154 – Andrew Clark Dec 03 '12 at 00:20

1 Answers1

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)]]
arshajii
  • 127,459
  • 24
  • 238
  • 287
  • Was just about to hit post on that same answer! gaw! +1. Even with the a,b names. – jdi Dec 03 '12 at 00:18
  • 1
    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 Dec 03 '12 at 00:21
  • 1
    @jdi And only in 2.x - in 3.x `zip()` produces generators, not lists, anyway. – Gareth Latty Dec 03 '12 at 00:27
  • @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! – jdi Dec 03 '12 at 00:27