我正在尝试打印由一些字符串分隔的3个整数变量。但它给了我一个错误
TypeError:+:' int'不支持的操作数类型和' str'。
我的尝试:
def unpack_values(grades):
first, *middle, last = grades
avg = sum(middle)/len(middle)
print(str(first)+"-------"+str(avg)+" ---- "+str(last))
unpack_values(['10', '20', '30', '40', '50'])
答案 0 :(得分:5)
尝试计算sum(middle)
时发生错误,因为middle
是字符串列表。您需要先将其转换为整数。
In [1]: def unpack_values(grades):
...: first, *middle, last = [int(g) for g in grades]
...: avg = sum(middle) / len(middle)
...: print('{} ------ {} ------ {}'.format(first, avg, last))
...:
In [2]: unpack_values(['10', '20', '30', '40', '50'])
10 ------ 30.0 ------ 50