这是我需要的: 用户输入 4 个逗号分隔的浮点值,我将使用这些值来创建我的矩形类。
这是我目前的做法:
1)通过input()获取用户输入
2) 将输入拆分()成列表
3)解压成变量
4)把那些变量(字符串)变成 float
此时我得到一个错误,因为逗号没有从字符串值中分离出来,所以试图转换成 float 会出现类型错误。我可以通过让 for each 循环分别遍历每个值并对其进行格式化来解决这个问题,但这不必要地复杂。我的问题是,我怎样才能以更干净、更简单的方式做到这一点?
def main():
x1,y1,width1,height1 = input("Enter x1, y1, width1, height1: ").split()
x1,y1,width1,height1 = float(x1),float(y1),float(width1),float(height1)
r1 = Rectangle2D(x1,y1,width1,height1)
x2,y2,width2,height2 = input("Enter x2, y2, width2, height2: ").split()
x2,y2,width2,height2 = float(x2),float(y2),float(width2),float(height2)
r2 = Rectangle2D(x2,y2,width2,height2)
class Rectangle2D:
def __init__(self, x = 0.0, y = 0.0, width = 0.0, height = 0.0):
self.x = x
self.y = y
self.width = width
self.height = height
样本运行:
Enter x1, y1, width1, height1: 9, 1.3, 10, 35.3
Traceback (most recent call last):
File "C:\Users\Lisa Dueker\Desktop\comp sci\week 9\HW\8.19.py", line 127, in <module>
main()
File "C:\Users\Lisa Dueker\Desktop\comp sci\week 9\HW\8.19.py", line 4, in main
x1,y1,width1,height1 = float(x1),float(y1),float(width1),float(height1)
ValueError: could not convert string to float: '9,'
最佳答案
好吧,你可以在没有任何中间变量的情况下做到这一点:
r = Rectangle(*map(float, input('enter stuff').split(',')))
或者如果你愿意,
r = Rectangle(*[float(x) for x in input('enter stuff').split(',')])
这使用 * 运算符(又名 splat 运算符)来 unpack the argument list放入您的 Rectangle
对象中。
关于python - 从 input() 中解压多个 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22641720/