正在尝试将输入转换为列表

2024-09-29 02:16:42 发布

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

我试图从用户那里获取2个点的输入并输出距离。 我无法将输入转换为输出列表。 我可能想错了,任何能帮我找到正确方向的帮助都是非常感谢的

import math
p1 = input("please enter x1 and y1: ")
p2 = input("please enter x2 and y2: ")

x1y1 = p1.split(',')
x2y2 = p2.split(',')
distance = math.sqrt( ((x1y1[0]-x2y2[0])**2)+((x1y1[1]-x2y2[1])**2) )

print(distance)

Tags: and用户距离列表inputmathdistancesplit
3条回答

首先将每个元素转换为int:

p1 = input("please enter x1 and y1: ")
p2 = input("please enter x2 and y2: ")

x1y1 = [int(x) for x in p1.split(',')]
x2y2 = [int(y) for y in p2.split(',')]
import math
p1 = input("please enter x1 and y1: ")
p2 = input("please enter x2 and y2: ")

x1y1 = [int(num) for num in p1.split(',')]
x2y2 = [int(num) for num in p2.split(',')]
distance = math.sqrt( ((x1y1[0]-x2y2[0])**2)+((x1y1[1]-x2y2[1])**2) )

print(distance)

Str应转换为int

您可以使用列表理解将输入转换为int,然后执行分解赋值,将其分配给两个不同的变量:

from math import sqrt

[x1, y1] = [int(n) for n in input("please enter x1 and y1: ").split()]
[x2, y2] = [int(n) for n in input("please enter x2 and y2: ").split()]

print(f"Distance: {sqrt((x1-x2)**2+(y1-y2)**2)}")

相关问题 更多 >