如何通过一行输入将多个整数存储在数组中?

0 投票
2 回答
783 浏览
提问于 2025-04-17 17:36
FirstName = raw_input("Please enter your first name: ")
Scores = map(int, raw_input("Please enter your four golf scores: ").split())
print "Score analysis for %s:" % FirstName
print "Your golf scores are: " + Scores
print "The lowest score is " + min(Scores)
print "The highest score is" +max(Scores)

我正在尝试把我用C++写的一个简单程序转换成Python。我想输入一个包含4个整数的数组,然后计算出最小值、最大值和其他一些东西。我希望用户能够像这样输入四个分数:“70 71 72 73”,然后把这四个分数存储为一个包含四个整数的数组(列表?)。

谢谢大家的帮助!

2 个回答

0

你可以用这两种格式来修改第四行:

print "Your golf scores are: ", Scores

或者

print "Your golf scores are: "+ str(Scores)
0

我在运行你的代码时看到的错误是关于输出的字符串格式问题,而不是输入的读取问题。下面是修正代码的一种方法。我把字符串和列表连接出错的地方改成了使用print语句中的逗号。我把两个字符串和整数连接出错的地方改成了使用字符串插值。

FirstName = raw_input("Please enter your first name: ")
Scores = map(int, raw_input("Please enter your four golf scores: ").split())
print "Score analysis for %s:" % FirstName
print "Your golf scores are:", Scores
print "The lowest score is %d" % min(Scores)
print "The highest score is %d" % max(Scores)

撰写回答