Why is my second variable (x2,y2) not defined while my first variable (x1,y1) is?

huangapple go评论104阅读模式
英文:

Why is my second variable (x2,y2) not defined while my first variable (x1,y1) is?

问题

  1. class Line():
  2. def __init__(self, coor1 , coor2):
  3. self.coor1 = coor1
  4. self.coor2 = coor2
  5. def distance(self):
  6. for (x1, y1), (x2, y2) in zip(self.coor1, self.coor2):
  7. distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
  8. return distance
  9. coordinate1 = (3,2)
  10. coordinate2 = (8,10)
  11. li = Line(coordinate1,coordinate2)
  12. li.distance()

嗨,我不太确定为什么第一个变量(x1,y1)能够被定义,而第二个变量(x2,y2)不能。我不太确定如何在for循环中包含两个元组,但是应该是两个都被定义或者两个都未定义的。谢谢!

英文:
  1. class Line():
  2. def __init__(self, coor1 , coor2):
  3. self.coor1 = coor1
  4. self.coor2 = coor2
  5. def distance(self):
  6. for x1,y1 in self.coor1, x2,y2 in self.coor2:
  7. distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
  8. return distance
  1. coordinate1 = (3,2)
  2. coordinate2 = (8,10)
  3. li = Line(coordinate1,coordinate2)
  4. 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循环。你不需要使用循环一次性分配多个值。只需这样做:

  1. class Line():
  2. def __init__(self, coor1 , coor2):
  3. self.coor1 = coor1
  4. self.coor2 = coor2
  5. def distance(self):
  6. x1,y1 = self.coor1
  7. x2,y2 = self.coor2
  8. distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
  9. return distance
  10. coordinate1 = (3,2)
  11. coordinate2 = (8,10)
  12. li = Line(coordinate1,coordinate2)
  13. print(li.distance())

由于元组包含两个值,它们将被分配给用逗号分隔的两个变量:

  1. x,y = (1,2)

等同于:

  1. x = 1
  2. y = 2

或者你可以直接使用以下代码:

  1. 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:

  1. class Line():
  2. def __init__(self, coor1 , coor2):
  3. self.coor1 = coor1
  4. self.coor2 = coor2
  5. def distance(self):
  6. x1,y1 = self.coor1
  7. x2,y2 = self.coor2
  8. distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
  9. return distance
  10. coordinate1 = (3,2)
  11. coordinate2 = (8,10)
  12. li = Line(coordinate1,coordinate2)
  13. print(li.distance())

Since the tuples contain two values, they will be assigned to the 2 variables separated by the comma:

  1. x,y = (1,2)

is same as

  1. x = 1
  2. y = 2

Or you could just:

  1. 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.

huangapple
  • 本文由 发表于 2023年7月27日 16:32:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定