Python如何添加整数(可能在列表中?)

2024-04-26 07:03:17 发布

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

我15岁,在学校做作业时,我要让“用户”输入一个整数列表,然后程序必须将列表中的整数相加,然后返回:

Total: $[sum of integers]

到目前为止,我已经做到了

^{pr2}$

但它总是返回错误:

Traceback (most recent call last):
  File "C:\Python33\Did I Spend Too Much.py", line 2, in <module>
    cost = int(cost)
ValueError: invalid literal for int() with base 10: '10 15 9 5 7'

其中'1015957'是我在测试中输入的整数。在

如有任何帮助,我们将不胜感激


Tags: ofintegers用户程序列表错误整数学校
3条回答
cost = cost.split()
total = sum([ int(i) for i in cost ])

你必须分析字符串。input将字符串返回为10 15 9 5 7,因此使用(space) and you will get list of str解析该字符串。将str的列表转换为int,然后求和。在

我可以给你们解决办法,但最好的办法是你们在学生时代尝试自己。如果有任何问题,请给出意见。在

你试图把空格也转换成整数,这是不可能的。相反,您需要拆分字符串,然后将所有单个元素转换为int:)

cost = cost.split()
cost = [ int(i) for i in cost ]
total = sum(total)

相关问题 更多 >