self.food_list = [['apple', 100, 'Fruit', 384.0], ['orange', 100, 'Fruit', 384.0]]
我想把索引3中的元素求和。
预期输出是Total calorie of all food is 768.0Kcal
但出现了以下错误:
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()
只需迭代食物清单的元素。 作为对罗宾爵士回答的改进:
我也编辑了
j +=
部分,这样它也可以处理2个以上的元素。在我在运行代码时没有发现任何问题(但是我不得不想象一下这个类,因为你没有给出它)。在
输出:“所有食物的总热量为768.0卡”
我用的是Python2.7
编辑1:
正如卢卡斯·安斯蒂格在你的帖子评论中指出的,“你的j+=j逻辑有一个缺陷”
您应该这样做:
^{pr2}$编辑2:
现在我有了您的全部代码,我可以强调两个问题:
您正在尝试对一个Food对象使用索引,但是您的Food对象不支持按您的方式构造索引,如果您确实想使用支持索引的对象,请阅读this (from doc)或{a2}。 无论如何,您可以通过访问Food对象实例的属性“carorie”来轻松解决这个问题。所以},但它不会工作,因为(见第2点)
j += i[3]
变成{Input返回一个字符串,因此i.carrie是一个字符串,您必须执行
j += float(i.calorie)
否则将得到一个TypeError(与Javascript不同,Python不接受字符串和整数连接)最后,您的代码变成:
输出:
我希望我在这方面有所帮助,但是,就像我在评论中说的,你真的应该读一些关于OOP的好材料,比如“headfirst”系列,或者如果你喜欢更具交互性的东西,Udemy上有很棒的课程和教程。在
相关问题 更多 >
编程相关推荐