访问python列表中对象的位置(3.5)

时间:2016-03-10 19:37:38

标签: python list python-3.x

真正基本的问题,但我似乎无法找到答案。如何从列表中获取对象的位置?

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

如果有人能向我解释为什么这样做不会很好。我不想要一个明确的答案,只是在正确的方向上轻推。

最佳

2 个答案:

答案 0 :(得分:2)

如果您正在讨论迭代列表并想要索引,您可以将列表传递给enumerate(),它将返回其索引,然后返回该项。

for index, item in enumerate(items):
    ...

或者,如果您只是想在列表中找到项目的索引,可以使用listToSearch.index(itemToFind)

答案 1 :(得分:1)

如您所见,

list.index如果找不到该对象,则不会返回0;它引发了ValueError例外。 (想想看:函数返回一个索引,0是一个有效的列表索引。)

你只需要捕捉异常:

try:
    self.ingredients.index(ingredient)
except ValueError:
    amounts[key] = 0 

amounts[key] += amount * (ingredient.nutrients[key])