I have list like this:
pp=[[0,0] , [-1,5], [2,3], [1,5], [3,6], [4,5], [5,3], [8,-2], [4, -4], [2, -5]]
And I want to extract x and y values in separate lists like:
ppx= [0, -1, 2, 1, 3, 4, 5, 8, 4, 2]
I think that list comprehensions is the most straightforward way:
xs = [p[0] for p in pp]
ys = [p[1] for p in pp]
Use zip()
to separate the coordinates:
ppx, ppy = zip(*pp)
This produces tuples; these are easily enough mapped to list
objects:
ppx, ppy = map(list, zip(*pp))
This works in both Python 2 and 3 (where the map()
iterator is expanded for the tuple assignment).
Demo:
>>> pp=[[0,0] , [-1,5], [2,3], [1,5], [3,6], [4,5], [5,3], [8,-2], [4, -4], [2, -5]]
>>> ppx, ppy = zip(*pp)
>>> ppx
(0, -1, 2, 1, 3, 4, 5, 8, 4, 2)
>>> ppy
(0, 5, 3, 5, 6, 5, 3, -2, -4, -5)
>>> ppx, ppy = map(list, zip(*pp))
>>> ppx
[0, -1, 2, 1, 3, 4, 5, 8, 4, 2]
>>> ppy
[0, 5, 3, 5, 6, 5, 3, -2, -4, -5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With