我想创建一个打印文件中某些值的平均值的程序。当我运行使用文件“cropdata.txt”我的代码,其中包含此:你如何使用sum()和列表项?
Lettuce 1 2 3
Tomato 6 5 1
我得到以下错误:
line_mean = (sum(line_parts[1:])/len(line_parts))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
我真的不知道这是为什么,因为我认为我已将所选元素转换为整数。
我的代码:
file = ('cropdata.txt')
with open(file, 'r') as file_numsort_1:
for line in file_numsort_1:
line = (line.rstrip(" \n"))
line_parts = line.split(' ')
for num in line_parts[1:]:
num=int(num)
line_mean = (sum(line_parts[1:])/len(line_parts))
print(line_mean)
'总和(地图(INT ,line_parts [1:]))',你想要用len(line_parts) - 1'除。 'num = int(num)'只重新绑定'num',而不是列表中的值。 –