Python2.7存储来自同一原始输入lin的浮点和字符串

2024-04-29 05:36:43 发布

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

我试图让Python2.7存储一行输入,其中包含一个字符串和三个浮点数,以便执行一些平均值,等等

示例输入:Tom 25 30 20

我试过了:

name, score1, score2, score3 = raw_input().split()
score1, score2, score3 = [float(score1),float(score2),float(score3)]

但是由于字符串的原因,它抛出了一个“无效文本”错误。另外,我的代码感觉笨重,有没有更简单的方法来实现这一点?在

谢谢你的帮助!在


Tags: 字符串name文本示例inputraw原因float
2条回答

你可以这样解决问题:

input = raw_input("Give me the input [name number number number]: ").split(" ")
name = input[0]
floats = map(float, input[1:])
print "I'm your name ", name
print "I'm your floats ", floats
print "I'm a sample average ", sum(floats)/len(floats)

您可以通过以下方式获得任何浮动:

^{pr2}$

你可以稍微重构一下,但是你所拥有的是有效的,并不是那么庞大或糟糕。在

>>> user_input = raw_input('Enter your name and three numbers: ').strip().split()
Enter your name and three numbers: Tom 25 30 20
>>> name = user_input[0]
>>> scores = map(float, user_input[1:])
>>> name
'Tom'
>>> scores
[25.0, 30.0, 20.0]

这样做意味着使用一个列表(下标为scores[0]scores[1]),而不是名为n1n2的变量(这总是建议您使用列表)。在

mapfloat一起使用意味着你不必写float(var)三次。在

您还可以考虑在用户输入上使用strip()。这通常是一个好主意,尤其是因为您隐式地分割了空白。在

相关问题 更多 >