【问题标题】:TypeError summing a list of integersTypeError 对整数列表求和
【发布时间】:2019-11-24 22:32:37
【问题描述】:

我想使用循环查找列表中元素的总和。如果输入不同的列表,我必须能够通用地应用它。

我尝试过简单的

print(sum(numbers)) 

然后它返回

TypeError:+ 的不支持的操作数类型:'int' 和 'str'。

当我尝试单独添加每个时,我发现列表发生了变化。原始列表是[1, 3, 5, 7, 9]。当我使用

添加每个元素时
int(numbers[0]) + int(number[1]) # ... 

当我到达索引 4 时,索引没有值。

【问题讨论】:

  • 欢迎来到 SO!我无法重现这一点——请显示您的实际列表和完整代码,以将问题重现为minimal reproducible example。您是否将这些数字作为偶然输入?我猜您可能忘记使用int(input("enter a number")) 或list(map(int, input("Enter a list of numbers separated by whitespace: ").split())) 将字符串输入转换为整数。谢谢。

标签: python-3.x list for-loop


【解决方案1】:

我有点不确定你的意思,因为你没有包含太多代码,但我相信我可以回答一部分。

如果没有看到您编写的代码,很难知道为什么会出现索引错误,但我想是因为您可能在添加它们时删除了它们。

也许可以尝试使用累加器变量,这会导致 python 代码看起来像

numbers = [1,2,3,4]
total = 0
for i in range(len(numbers)): #loops through for exactly the number of items in the list
    sum = total + numbers[i]

这不会更改列表中的任何项目,保持不变,并为您留下等于列表总和的变量 sum。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 2015-03-18
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多