不支持的操作数 +
Unsupported operand +
我正在尝试编写一个可以添加组合值的程序,但我收到此错误消息:
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 所以我看不出问题在哪里
里面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]
但实际上我在想这些组合是否正确
使用
somme = somme + l[i][0][1]
而不是
somme = somme + l[i][1]
我正在尝试编写一个可以添加组合值的程序,但我收到此错误消息:
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 所以我看不出问题在哪里
里面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]
但实际上我在想这些组合是否正确
使用
somme = somme + l[i][0][1]
而不是
somme = somme + l[i][1]