【问题标题】:Unsupported operand +不支持的操作数 +
【发布时间】:2021-04-26 12:29:14
【问题描述】:

我正在尝试编写一个添加组合值的程序,但我收到此错误消息:

TypeError: unsupported operand type(s) for +: 'int' and 'tuple

这是我的代码:

from itertools import combinations

# values are 32, 20, 5, 18
objects = [
    ("golden purse", 32, 2),
    ("gold", 20, 5),
    ("iron statue", 5, 1),
    ("iron sword", 18, 6),
]


def combinaisons(l):
    tmp = []
    for i in range(1, len(l) + 1):
        tmp += list(combinations(l, i))
    return tmp


comb = combinaisons(objects)


def calc_values(l):
    somme = 0
    for c in range(len(l)):
        for i in range(len(l[c])):
            somme = somme + l[i][1]
        print(somme)


calc_values(comb)

“l[i][1]”应该是32这样的整数,所以我看不出问题出在哪里

【问题讨论】:

  • “应该是”...你检查过它吗?例如。只需print之前就可以了吗?
  • 它说tuple index out of range 但我不知道 l[0][1] 是如何超出范围的..
  • 好吧,如果你做了print(l)...

标签: python list loops tuples range


【解决方案1】:

calc_values()l里面是

[ ( ('golden purse', 32, 2), ) , ...
^ ^ ^                       ^
| | tuple = l[0][0]         nothing = l[0][1]
| tuple = l[0]
array = l

l[0] 是一个由另一个元组组成的元组,什么都没有。 l[0][0] 是最里面的元组,l[0][1] 什么都不是。这就是您要访问的内容。

像 Pycharm 这样的 IDE 为您提供了调试的能力。它将在异常处停止,并让您能够动态检查变量。充分利用它。

根据你想要总结的内容,你需要

somme = somme + l[i][0][1]

somme = somme + l[i][0][2]

但实际上我想知道这些组合是否正确。

【讨论】:

    【解决方案2】:

    使用

    somme = somme + l[i][0][1]
    

    而不是

    somme = somme + l[i][1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      相关资源
      最近更新 更多