【发布时间】:2022-01-01 10:30:09
【问题描述】:
我编写了一个程序,它采用三个示例对象的元组(不确定它们是否真的是对象,但我在这里将它们标记为这样),并将元组或其中的项目与“收藏夹”元组。但是,当我运行它时:
import random
favorite_food = ['sushi', 'spaghetti', 'pizza', 'hamburgers', 'sandwiches']
favorite_taste = ['spicy', 'sweet', 'savory', 'sour', 'bitter', 'salty']
chosen_ff = random.choice(favorite_food)
chosen_ft = random.choice(favorite_taste)
test_food1 = ('salty', 'pizza')
test_food2 = ('sweet', 'sandwiches')
test_food3 = ('sour', 'sushi')
foods = (test_food1, test_food2, test_food3)
favorites = (chosen_ft, chosen_ff)
def foodresults():
points = 0
for food in foods:
for item in food:
print(food[0], food[1])
if item in favorites:
print("You got a match, nice job! +1 point")
points = points + 1
elif food == favorites:
print("Wow, it couldn't have enjoyed it more! +2 points")
points = points + 2
else:
print("It didn't like it very much...")
foodresults()
但是,当我这样做时,它总是会打印两次预期的消息,一次用于第一项,一次用于第二项。
salty pizza
You got a match, nice job! +1 point
salty pizza
It didn't like it very much...
sweet sandwiches
It didn't like it very much...
sweet sandwiches
It didn't like it very much...
sour sushi
It didn't like it very much...
sour sushi
You got a match, nice job! +1 point
如果我continue每次到达第二个项目,它就会把它从评分系统中取出,只检查第一个项目,反之亦然。有没有一种方法可以检查满足if item in favorites 条件的两个项目,并且只打印一行?
【问题讨论】:
-
chosen_ft和chosen_ff未定义。 -
它们是在我遗漏的部分代码中定义的,是从列表中随机选择的。我应该把它包括在问题中吗?
-
你应该包含一个minimal reproducible example。
-
不要使用名称
object作为python 关键字的变量
标签: python for-loop debugging tuples nested-loops