Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract x and y values from a list

Tags:

python

list

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]
like image 968
f.ashouri Avatar asked Jan 22 '14 12:01

f.ashouri


2 Answers

I think that list comprehensions is the most straightforward way:

xs = [p[0] for p in pp]
ys = [p[1] for p in pp]
like image 76
Nigel Tufnel Avatar answered Oct 24 '22 11:10

Nigel Tufnel


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]
like image 34
Martijn Pieters Avatar answered Oct 24 '22 10:10

Martijn Pieters