简体   繁体   中英

How can I manipulate cartesian coordinates in Python?

I have a collection of basic cartesian coordinates and I'd like to manipulate them with Python. For example, I have the following box (with coordinates show as the corners):

0,4---4,4

0,0---4,0

I'd like to be able to find a row that starts with (0,2) and goes to (4,2). Do I need to break up each coordinate into separate X and Y values and then use basic math, or is there a way to process coordinates as an (x,y) pair? For example, I'd like to say:

New_Row_Start_Coordinate = (0,2) + (0,0)
New_Row_End_Coordinate = New_Row_Start_Coordinate + (0,4)

Sounds like you're looking for a Point class. Here's a simple one:

class Point:
  def __init__(self, x, y):
    self.x, self.y = x, y

  def __str__(self):
    return "{}, {}".format(self.x, self.y)

  def __neg__(self):
    return Point(-self.x, -self.y)

  def __add__(self, point):
    return Point(self.x+point.x, self.y+point.y)

  def __sub__(self, point):
    return self + -point

You can then do things like this:

>>> p1 = Point(1,1)
>>> p2 = Point(3,4)
>>> print p1 + p2
4, 5

You can add as many other operations as you need. For a list of all of the methods you can implement, see the Python docs .

depending on what you want to do with the coordinates, you can also misuse the complex numbers:

import cmath

New_Row_Start_Coordinate = (0+2j) + (0+0j)
New_Row_End_Coordinate = New_Row_Start_Coordinate + (4+0j)

print New_Row_End_Coordinate.real
print New_Row_End_Coordinate.imag

Python doesn't natively support elementwise operations on lists; you could do it via list comprehensions or map but that's a little clunky for this use case. If you're doing a lot of this kind of thing, I'd suggest looking at NumPy .

For a = (0,2) and b = (0,0) a + b will yield (0, 2, 0, 0) , which is probably not what you want. I suggest to use numpy 's add function: http://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html

Parameters : x1, x2 : array_like

Returns: The sum of x1 and x2, element-wise. (...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM