我对python和一般编程都不熟悉,我很难理解为什么我不能访问我创建的列表的x,y坐标作为数学模块距离公式中的变量
这里是我的全部代码,但是定义函数closestpt
的步骤是我挂断的地方,在函数中,ranlist.x
,ranlist.y
是我得到
AttributeError: list object has no attribute 'x'
有人能解释一下为什么ranlist
没有“x”和“y”作为属性,以及我如何访问列表ranlist
中的x,y点吗?当我逐步完成代码和调试时,我可以看到生成的随机浮点值
import math
class Point():
def __init__(self, x, y, z=0):
self.x=x
self.y=y
self.z=z
self.dem=2
if (z!=0):
self.dem=3
def print_coordinate(self):
print "The x coordinate is %s, the y coordinate is %s, and the z coordinate is %s" % (self.x, self.y, self.z)
def calc_distance(self, next1):
try:
if (self.z==0):
dx = self.x - next1.x
dy = self.y - next1.y
return math.hypot(dx,dy)
else:
threedist = ((self.x - next1.x)^2 + (self.y - next1.y)^2 + (self.z - next1.z)^2)
return math.sqrt(threedist)
except(SyntaxError, IndexError, TypeError) as e:
print e
cord1 = Point(0,1,4)
cord2 = Point(0,4,0)
print cord1.print_coordinate()
print cord1.calc_distance(cord2)
import random
a = 10
b = 20
val = random.uniform(a,b)
ranlist = []
def ranpoint(num_point, dimension, lower_bound, upper_bound):
for i in range(num_point):
x = random.uniform(lower_bound, upper_bound)
y = random.uniform(lower_bound, upper_bound)
ranlist.append(Point(x,y,0))
return ranlist
print ranpoint
print ranpoint(100, "2d", 0, 100)
rantest = ranpoint(100, '2d', 0, 100)
def closestpt():
cordt = Point(50,50)
dist1 = []
for i in range(0, 100):
ndx = cordt.x - ranlist.x
ndy = cordt.y - ranlist.y
dist2 = math.hypot(ndx,ndy)
dist1.append(dist2)
return dist1
print closestpt()
你有} 。你
ranlist
,这是一个^{append
对它Point
。所以现在ranlist
里面有一个Point
类型的对象要访问此对象,可以运行
ranlist[0].x
和ranlist[0].y
,这将访问列表的第一个成员(在索引0
)并分别检索x
和y
的值相关问题 更多 >
编程相关推荐