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

标签 python variable-assignment

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

Total: $[sum of integers]

到目前为止,我有

cost = input("Enter the expenses: ")
cost = int(cost)
total = sum(i)
print("Total: $" + i)

但它一直返回错误:

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'

其中 '10 15 9 5 7' 是我在测试中输入的整数。

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

最佳答案

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

关于Python - 如何添加整数(可能在列表中?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22526799/

相关文章:

java - boolean 值 and= 赋值运算符含义

python - 检查字符串是否仅包含字符/符号列表中的字符?

python - 为什么 selenium webdriver Firefox 不适用于非特权用户?

java - 为什么将一个变量赋值给另一个变量?

javascript - JavaScript 中的 `x = y, z` 逗号赋值

Matlab:分配给具有列\行索引对的矩阵

typescript - 为什么 TypeScript 在分配给新的空数组时不暗示数组类型?

python - django 或 postgresql 的缓存问题

python - Plotly:如何对不同的痕迹使用变换颜色?

python - FutureWarning : in the future, 类 boolean 数组将作为 boolean 数组索引处理