0

Let's say, I have a list of x,y coordinates like:

all_coordinates = [x1,y1,x2,y2,x3,y3,x4,y4...]

And there is a method:

def rotate_xy_by_theta(self, x, y, theta):
    # does the maths
    returns new_x, new_y

which returns the new_x,new_y position for each pair of coordinates given a particular x, y input values for a given theta.

I now want to iterate through all items in the above list in pair and generate a new list modified_coordinates.

I can do this easily with a traditional for-loop.

Can this be done with the map function ?

Something like:

theta = 90    
modified_coordinates = map(self.rotate_xy_by_theta(x, y, theta), all_coordinates)

My issue is how to get x,y values in pair in the above map function.

bhaskarc
  • 9,269
  • 10
  • 65
  • 86
  • Why don't you use a better structure to store your coordinates? Even something like `all_coordinates = [[x1,x2,x3,x4],[y1,y2,y3,y4]]` – David Zemens Aug 22 '15 at 19:47
  • Oh I wish I could do it. I get `all_coordinates` from an api which is not under my control. – bhaskarc Aug 22 '15 at 19:48
  • 2
    well you can get the x coords by `x_coords = all_coordinates[::1]` and the y coords by `y = all_coordinates[1::2]` – David Zemens Aug 22 '15 at 19:54

1 Answers1

2

You cannot do what you want with map() directly, because you are not applying a function to each individual value in your input. You need to pair up the values in the input, and add an extra argument to your function each time. Your function also returns a tuple of coordinates, depending on your needs you may have to flatten out the results again.

Using the tools from Iterating over every two elements in a list and a list comprehension is the better option here:

theta = 90
per_two = zip(*([iter(all_coordinates)] * 2))
modified_coordinates = [self.rotate_xy_by_theta(x, y, theta) for x, y in per_two]

This gives you a list of (new_x, new_y) tuples, arguably a better format to continue processing. If you do need this flattened out again, you can add another loop:

modified_coordinates = [coord for x, y in per_two for coord in self.rotate_xy_by_theta(x, y, theta)]

If you need modified_coordinates to be a lazy generator (like map() is in Python 3) you can make it a generator expression instead:

modified_coordinates = (self.rotate_xy_by_theta(x, y, theta) for x, y in per_two)

or flattened:

modified_coordinates = (coord for x, y in per_two for coord in self.rotate_xy_by_theta(x, y, theta))
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343