真正基本的問題,但我似乎無法找到答案。我如何從列表中獲取對象的位置?訪問python列表中的對象的位置(3.5)
for amount, ingredient in self.ingredients:
for key in ingredient.nutrients:
print(amount*(ingredient.nutrients[key]))
if self.ingredients.index(ingredient) == 0:
amounts[key] = amount*(ingredient.nutrients[key])
else:
amounts[key] = amount*(ingredient.nutrients[key]) + amounts[key]
對象有問題(self.ingredients)
[(300, Ingredient(Egg, {'fat': 0.0994, 'cholesterol': 0.00423, 'carbs': 0.0077, 'protein': 0.1258})), (0.25, Recipe(Bread, [(820, Ingredient(Flour, {'fat': 0.0994, 'cholesterol': 0.00423, 'carbs': 0.0077, 'protein': 0.1258})), (30, Ingredient(Oil, {'fat': 0.0994, 'cholesterol': 0.00423, 'carbs': 0.0077, 'protein': 0.1258})), (36, Ingredient(Sugar, {'fat': 0.0994, 'cholesterol': 0.00423, 'carbs': 0.0077, 'protein': 0.1258})), (7, Ingredient(Yeast, {'fat': 0.0994, 'cholesterol': 0.00423, 'carbs': 0.0077, 'protein': 0.1258})), (560, Ingredient(Water, {'fat': 0.0994, 'cholesterol': 0.00423, 'carbs': 0.0077, 'protein': 0.1258}))]))]
錯誤:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-54-85a3df33671e> in <module>()
56 print(basic_french_toast.ingredients)
57
---> 58 print(basic_french_toast.nutrients)
<ipython-input-54-85a3df33671e> in nutrients(self)
40 for key in ingredient.nutrients:
41 print(amount*(ingredient.nutrients[key]))
---> 42 if self.ingredients.index(ingredient) == 0:
43
44 amounts[key] = amount*(ingredient.nutrients[key])
ValueError: Ingredient(Egg, {'fat': 0.0994, 'cholesterol': 0.00423, 'carbs': 0.0077, 'protein': 0.1258}) is not in list
如果任何人都可以向我解釋爲什麼這不工作,這將是巨大的。我不想明確的答案只是朝着正確的方向推動。
最佳
的枚舉(項目)幫了不少忙謝謝 – njBernstein
而@chepner是正確的,如果用'list.index()'搜索的項不存在,它會引發一個'ValueError'。您可以先檢查該項目是否實際位於列表中,或者預期有異常。 –