[英]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. 我有一组基本的笛卡尔坐标,我想用Python操作它们。 For example, I have the following box (with coordinates show as the corners): 例如,我有以下框(坐标显示为角):
0,4---4,4 0,4 --- 4,4
0,0---4,0 0,0 --- 4,0
I'd like to be able to find a row that starts with (0,2) and goes to (4,2). 我希望能够找到一个以(0,2)开头并转到(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? 我是否需要将每个坐标分解为单独的X和Y值然后使用基本数学,或者有没有办法将坐标作为(x,y)对处理? 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. 听起来你正在寻找一个Point类。 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 . 有关您可以实现的所有方法的列表,请参阅Python文档 。
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; Python本身不支持列表上的元素操作; you could do it via list comprehensions or map
but that's a little clunky for this use case. 你可以通过列表推导或map
来做到这一点但这对于这个用例来说有点笨拙。 If you're doing a lot of this kind of thing, I'd suggest looking at NumPy . 如果你做了很多这样的事情,我建议你看看NumPy 。
For a = (0,2)
and b = (0,0)
a + b
will yield (0, 2, 0, 0)
, which is probably not what you want. 对于a = (0,2)
和b = (0,0)
a + b
将产生(0, 2, 0, 0)
,这可能不是你想要的。 I suggest to use numpy
's add
function: http://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html 我建议使用numpy
的add
功能: http : //docs.scipy.org/doc/numpy/reference/generated/numpy.add.html
Parameters : x1, x2 : array_like 参数:x1,x2:array_like
Returns: The sum of x1 and x2, element-wise. 返回:x1和x2之和,以元素为单位。 (...) (......)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.