无法从列表中获取返回的x,y浮点值以在点分布中使用

2024-10-01 04:44:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python和一般编程都不熟悉,我很难理解为什么我不能访问我创建的列表的x,y坐标作为数学模块距离公式中的变量

这里是我的全部代码,但是定义函数closestpt的步骤是我挂断的地方,在函数中,ranlist.xranlist.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()

Tags: selfcoordinatereturnisdefrandommathpoint
1条回答
网友
1楼 · 发布于 2024-10-01 04:44:55

你有ranlist,这是一个^{}。你append对它Point。所以现在ranlist里面有一个Point类型的对象

要访问此对象,可以运行ranlist[0].xranlist[0].y,这将访问列表的第一个成员(在索引0)并分别检索xy的值

相关问题 更多 >