[英]Python - Write Co-ordinates into array
我想知道如何最好地將x,y坐標寫入數組中?
我也不知道陣列會變成多大...
也許,還有其他更易於使用的數據結構嗎?
謝謝你的幫助。
您可以將包含x,y坐標的元組(X,Y)插入列表中。
>>>l=[]
>>>coords = tuple([2,4])
>>>l.append(coords)
>>>l
[(2,3)]
my_coords = [(1, 2), (3, 4)]
my_coords.append((5, 6))
for x, y in my_coords:
print(x**2 + y**2)
坐標的一些例子
單位圓內的點
my_coords = [(0.5, 0.5), (2, 2), (5, 5)]
result = []
for x, y in my_coords:
if x**2 + y**2 <= 1:
result.append((x, y))
產生一個圓
from math import sin, cos, radians
result = []
for i in range(360):
x = cos(radians(i))
y = -sin(radians(i))
result.append((x, y))
如果您事先知道數據的大小,請使用numpy數組。
import numpy
arr = numpy.array([ [x,y] for x,y in get_coords() ])
如果您需要即時添加數據,請使用元組列表。
l = []
for x,y in get_coords():
l.append((x,y))
一個元組可能足以完成簡單的任務,但是您也可以為此目的創建一個Coordinate
類。
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Coordinate({0.x:d}, {0.y:d})'.format(self)
>>> coord = Coordinate(0, 0)
Coordinate(0, 0)
>>> coord.x = 1
>>> coord.y = 2
>>> coord
Coordinate(1, 2)
>>> coord.x
1
>>> coord.y
2
使用以下__repr__
方法:
def __repr__(self):
return 'Coordinate(%d, %d)'.format(self)
浮點坐標將按原樣存儲,但是__repr__
方法將對其進行舍入。 只需將:d
替換為:.2f
(與%
相同),其中2
是要顯示的小數點數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.