【问题标题】:Operand error when using an integer in a list在列表中使用整数时出现操作数错误
【发布时间】:2022-02-02 01:54:16
【问题描述】:

我一直在尝试处理这段代码几个小时,但每次都在同一点上。基本上我正在尝试将数组中的所有值相加。但是,它一直说整数和列表的操作数不受支持。我很困惑为什么会这样说,因为列表由整数组成。这是在 python 中。

hours = [0,0,0,0,0]

i=0 
while i < 5:
    print (days[i])
    hours [i] = int(input('How many hours did you work for the day above? \n'))
    i+=1
    print('\n')
    
for x in range(len(days)):
    print('\n')
    print (days [x])
    print (hours[x])

total = 0
for x in hours:
    total += hours

以上是我认为是问题的代码部分

    total += hours
TypeError: unsupported operand type(s) for +=: 'int' and 'list'

以上是我不断收到的错误

【问题讨论】:

  • 您想在该语句中添加xhours 是您正在迭代的列表,x 是单个项目。但是,您可以不编写循环,而是执行 total = sum(hours)
  • @U 换句话说,应该是total += hours,而不是total += x

标签: python list integer operands


【解决方案1】:

正如@kindall@Ben Grossmann 正确指出的那样,您正在尝试将数字添加到列表中:

total += hours
  • total 是一个整数 (total = 0)
  • hours 是一个列表 (hours = [0,0,0,0,0])

把你的代码改成这样让它工作:

for x in hours:
    total += x

旁注:

有一种优雅的方法可以获取数字列表的总和:

total = sum(hours)

sum() 是一个内置函数(它随 Python 开箱即用)。你可以阅读更多关于它的信息here

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多