0

I have a list of tuples of x and y coordinates such as: [(1,2), (3,4), (5,6)] and I want to manipulate the list to become a 2xN matrix(depending on how many numbers) so that I have a list of just the x coordinates and then the y coordinates. Basically I want to output: [(1,3,5), (2,4,6)] through a function, but am not exactly sure how to do so.

Angie
  • 183
  • 3
  • 13

1 Answers1

0
list(zip(*[(1, 2), (3, 4), (5, 6)]))

will output:

[(1, 3, 5), (2, 4, 6)]

>>> a = [(1, 2), (3, 4), (5, 6)]

>>> zip(*a) # Returns a zipped object. 
<zip object at 0x10c9f5540>

>>> print(*a) # "Star a" unpacks the list.
(1, 2) (3, 4) (5, 6)

>>> print(a[0], a[1], a[2]) # Above is equivalent to:
(1, 2) (3, 4) (5, 6)

>>> b, c = [1, 2], [3, 4]

>>> list(zip(b, c))
[(1, 3), (2, 4)] # Zips the inputs of both lists in the pattern (b1, c1) and (b2, c2). list() converts the "zip" generator to a list. 

>>> list(zip(*a)) 
[(1, 3, 5), (2, 4, 6)] # Zips the wanted ints with the logic above.
felipe
  • 7,324
  • 2
  • 28
  • 37
  • would this also work if I were to have a list of lists? Such as [[(1, 2), (3, 4), (5, 6)], [(3,8), (4,5)]] and instead I wanted [(1,3,5,3,4), (2,4,6,8,5)]? – Angie Jun 01 '20 at 01:00
  • yup! it should, as zip will "transform" `(a, b), (c, d), (e, f)` into `(a, c, e), (b, d, f)`. – felipe Jun 01 '20 at 03:36