英文:
Why is my second variable (x2,y2) not defined while my first variable (x1,y1) is?
问题
class Line():
def __init__(self, coor1 , coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
for (x1, y1), (x2, y2) in zip(self.coor1, self.coor2):
distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
return distance
coordinate1 = (3,2)
coordinate2 = (8,10)
li = Line(coordinate1,coordinate2)
li.distance()
嗨,我不太确定为什么第一个变量(x1,y1)能够被定义,而第二个变量(x2,y2)不能。我不太确定如何在for循环中包含两个元组,但是应该是两个都被定义或者两个都未定义的。谢谢!
英文:
class Line():
def __init__(self, coor1 , coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
for x1,y1 in self.coor1, x2,y2 in self.coor2:
distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
return distance
coordinate1 = (3,2)
coordinate2 = (8,10)
li = Line(coordinate1,coordinate2)
li.distance()
Hi, I am not too sure why (x2,y2) wasn't able to be defined while the first variable (x1,y1) was. I am not too sure how to include both tuples in the for loop, but shouldn't both be defined or none of them are defined? Thanks!
答案1
得分: 3
你没有正确使用for循环。你不需要使用循环一次性分配多个值。只需这样做:
class Line():
def __init__(self, coor1 , coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
x1,y1 = self.coor1
x2,y2 = self.coor2
distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
return distance
coordinate1 = (3,2)
coordinate2 = (8,10)
li = Line(coordinate1,coordinate2)
print(li.distance())
由于元组包含两个值,它们将被分配给用逗号分隔的两个变量:
x,y = (1,2)
等同于:
x = 1
y = 2
或者你可以直接使用以下代码:
return sum([(i[0] - i[1])**2 for i in zip(self.coor1, self.coor2)])**0.5
这适用于n维向量。
英文:
You are not using the for loop correctly. You don't need a loop to assign multiple values at once. Just do:
class Line():
def __init__(self, coor1 , coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
x1,y1 = self.coor1
x2,y2 = self.coor2
distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
return distance
coordinate1 = (3,2)
coordinate2 = (8,10)
li = Line(coordinate1,coordinate2)
print(li.distance())
Since the tuples contain two values, they will be assigned to the 2 variables separated by the comma:
x,y = (1,2)
is same as
x = 1
y = 2
Or you could just:
return sum([(i[0] - i[1])**2 for i in zip(self.coor1, self.coor2)])**0.5
And that would work with n-dimensional vectors.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论