我想創建一個打印文件中某些值的平均值的程序。當我運行使用文件「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',而不是列表中的值。 –