Reputation: 327
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.
Upvotes: 0
Views: 86
Reputation: 4171
The shortest possible solution, though perhaps not as intuitive.
list(zip(*sum(b,[])))
Upvotes: 0
Reputation: 260
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))
Upvotes: 1
Reputation: 78690
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)]
Upvotes: 1
Reputation: 88236
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)]
Upvotes: 2