gpt4 book ai didi

python - 类型错误 : 'Food' object does not support indexing

转载 作者:行者123 更新时间:2023-12-01 02:30:24 25 4
gpt4 key购买 nike

self.food_list = [['apple', 100, 'Fruit', 384.0], ['orange', 100, 'Fruit', 384.0]]

我想对索引 3 中的元素求和。预期输出为所有食物的总热量为 768.0Kcal

def totalCalorie(self):
for i in range(0, len(self.food_list)):
j = self.food_list[i][3]
j += j
print("Total calorie of all food is {}Kcal".format(j))

但是出现了以下错误:

Traceback (most recent call last):
File "D:/PythonTim/Assignment/nutritionDriver.py", line 60, in <module>
main()
File "D:/PythonTim/Assignment/nutritionDriver.py", line 43, in main
patient.totalCalorie()
File "D:\PythonTim\Assignment\nutritionApp.py", line 132, in totalCalorie
j = self.food_list[i][3]
TypeError: 'Food' object does not support indexing

我想做的是,当用户想要合计列表中的所有卡路里时,系统将显示列表中的总卡路里。

还有其他方法吗?谢谢!

编辑:

class Food:
def __init__(self, name, quantity, category, calorie):
self.name = name
self.quantity = quantity
self.category = category
self.calorie = calorie

class FoodList:

def __init__(self):
self.food_list = []

def totalCalorie(self):
j=0
for i in self.food_list:
j += i[3]
print("Total calorie of all food is {}Kcal".format(j))

def addFood(self, newfruit):
self.food_list.append(newfruit)

name = input("Name? ")
quantity = input("Quantity? ")
category = input("Category? ")
calorie = input("Calorie? ")
f = Food(name, quantity, category, calorie)
patient = FoodList()
patient.addFood(f)

name1 = input("Name? ")
quantity1 = input("Quantity? ")
category1 = input("Category? ")
calorie1 = input("Calorie? ")
f1 = Food(name1, quantity1, category1, calorie1)
patient.addFood(f1)

patient.totalCalorie()

最佳答案

只需迭代 food_list 的元素即可。作为对罗宾爵士答案的改进:

class Food:
food_list = []

def totalCalorie(self):
j=0
for i in self.food_list:
j += i[3]
print("Total calorie of all food is {}Kcal".format(j))

def addFood(self,newfruit):
self.food_list.append(newfruit)


f = Food()
f.addFood(['banana', 100, 'Fruit', 100.0])
f.addFood(['orange', 100, 'Fruit', 384.0])
f.totalCalorie()

我也编辑了 j += 部分,以便它也适用于 2 个以上的元素。

关于python - 类型错误 : 'Food' object does not support indexing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46890647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com