Здесь:
for food in menu:
if any(elem in removed_from_meal for elem in food):
menu.remove(food)
Вы модифицируете (.remove()
) список, по которому вы перебираете.Это ваша (основная) проблема.
Чтобы упростить проблему, рассмотрите следующий код:
lst = [1,2,3,4,5,6,7,8,9,10]
for x in lst:
print(x)
if x == 2:
print("Removing 2")
lst.remove(x)
Какие выходные данные:
1
2
Removing 2
4
5
6
7
8
9
10
Что произошлодо 3? Он был "пропущен", потому что вы изменили список, перебирая его.(На самом деле, удалив 2, вы сместили индекс 3).
Вы можете изменить это на что-то вроде:
acceptable_meals = []
for meal in menu:
if not any(food in removed_from_meal for food in meal):
acceptable_meals.append(meal)
или
acceptable_meals = []
for meal in menu:
if any(food in removed_from_meal for food in meal):
continue
acceptable_meals.append(meal)
При этом, я мог бы изменить весь объект, чтобы он выглядел примерно так:
pepper = "pepper"
salt = "salt"
meat = "meat"
chicken = "chicken"
tomato = "tomato"
cucumber = "cucumber"
tye = "tye"
# We can define the menu all at once, as a list of lists, instead of appending
# multiple separate sublists.
menu = [
[pepper, salt, meat],
[chicken, tomato, cucumber],
[pepper, chicken, tomato],
[salt, tomato, cucumber],
[meat, tomato],
[pepper, tye]
]
removed_from_meal = []
while True:
bad_ingredient = input("Please tell me what foods you don't like. When you're finished, type 0 to quit this: ")
if bad_ingredient == "0":
break
# Otherwise, add it to the food "blacklist"
removed_from_meal.append(bad_ingredient)
print("You have asked to remove {} from your meal.".format(removed_from_meal))
# Create a new list, which we'll populate if none of the food it contains is blacklisted
acceptable_meals = []
for meal in menu:
if not any(food in removed_from_meal for food in meal):
acceptable_meals.append(meal)
print("You can now choose {} meals from the menu:".format(len(acceptable_meals)))
for meal in acceptable_meals:
print(meal)