zell
zell

Reputation: 10204

Drawing points with matplotlib

I have a list of points in the form of

points=[(x1,y1),...(xn,yn)...]

I am looking for a pythonic way to transform the list into

 x=[x1,...xn] y=[y1,...yn]

One way to do it would be

x = map (lambda x: x[1],points)

However, maybe there is a more pythonic way to directly draw from "points" mentioned above?

Upvotes: 0

Views: 62

Answers (2)

error
error

Reputation: 2471

In addition to mehrdad-pedramfar answer:

If using numpy is not a problem you can convert your list of tuples to a numpy array and then just use indexing.

import numpy as np

short_example = np.array([(1,2),(2,4),(4,6)])
short_example[:,0]

gives a numpy array of all x values:

array([1, 2, 4])

short_example[:,1]

gives a numpy array of all y values:

array([2, 4, 6])

Upvotes: 1

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

You can do something like this:

x = []
y = []
for point in points:
   x.append(point[0])
   y.append(point[1])

or:

x,y = [i[0] for i in points],  [i[1] for i in points]

but the best way is to use zip:

x,y = zip(*points)

zip is better than map and it is faster, you should define a function in map with lambda. so I think the best way to do this is with zip.

Upvotes: 4

Related Questions