Not*_*Spy 0 python math list distance
我正在编写一些如下所示的代码:
import math
def get_coord_distance():
c_1 = input('What is the coordinate of the first point?\n').split(',')
c_2 = input('What is the coordinate of the second point?\n').split(',')
p = []
q = []
p.append(c_1)
q.append(c_2)
coordinate_distance = math.dist(p, q)
if p == q:
print('The two points equal each other. The distance is 0.')
exit()
return coordinate_distance
res = get_coord_distance()
print(res)
Run Code Online (Sandbox Code Playgroud)
math.dist 使用两个列表,并使用距离公式并输出两个列表之间的距离。这看起来像:
p = [3, 14]
q = [1, 59]
print(math.dist(p, q))
Run Code Online (Sandbox Code Playgroud)
这将输出一个浮点数,如下所示:
45.04442251822083
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码(第一个代码块)时,我收到一条错误消息。
TypeError: must be real number, not list
Run Code Online (Sandbox Code Playgroud)
我在这里犯了什么错误?我认为这是数学模块的错误,但我不确定。
小智 6
你错了两件事。首先,您需要转换您的输入。其次,您不应该附加到 p 和 q 而是扩展。尝试下面的代码
请注意,不要扩展空列表。我已经使用map函数来获取转换后的坐标并直接分配给 P & Q
import math
def get_coord_distance():
c_1 = input('What is the coordinate of the first point?\n').split(',')
c_2 = input('What is the coordinate of the second point?\n').split(',')
p = map(int, c_1)
q = map(int, c_2)
coordinate_distance = math.dist(p, q)
if p == q:
print('The two points equal each other. The distance is 0.')
exit()
return coordinate_distance
res = get_coord_distance()
print(res)
Run Code Online (Sandbox Code Playgroud)