0

I have a list of lists containing tuples of x and y coordinates such as [ [(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)] ] and I want to combine them in such a way where the output contains all the x coordinates together and all the y coordinates together. Essentially I'm trying to make the output be [(1,3,5,7,0), (2,4,6,8,5)] so that it is a 2xN matrix. I tried to do list(zip(*b) where b = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]] (the original list), but that has not given me the correct output.

Angie
  • 183
  • 3
  • 13

4 Answers4

2

You first need to flatten the nested list. You can use itertools.chain:

from itertools import chain

list(zip(*chain.from_iterable(b)))
# [(1, 3, 5, 7, 0), (2, 4, 6, 8, 5)]
yatu
  • 86,083
  • 12
  • 84
  • 139
1

Your approach is correct, you just have to flatten your input list first.

>>> lst = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]]
>>> lst_flat = [x for sublist in lst for x in sublist]
>>> list(zip(*lst_flat))
[(1, 3, 5, 7, 0), (2, 4, 6, 8, 5)]
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

Create a flat list first and then create a list of two tuples

a = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]]

flat_list = [item for sublist in a for item in sublist]
b = list(zip(*flat_list))
challa420
  • 260
  • 1
  • 12
0

The shortest possible solution, though perhaps not as intuitive.

list(zip(*sum(b,[])))
Mercury
  • 3,417
  • 1
  • 10
  • 35