我撰寫了一個程式,該程式采用三個示例物件的元組(不確定它們是否真的是物件,但我已經將它們標記為此處),并將元組或其中的專案與“收藏夾”進行比較元組。但是,當我運行它時:
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
如果 Icontinue每次到達第二項,它就會將其從評分系統中取出,只檢查第一項,反之亦然。有沒有一種方法可以檢查兩個專案是否符合if item in favorites條件,只列印一行?
uj5u.com熱心網友回復:
你可以重構代碼以使用單一回路和zip map sum計算匹配的數量。
請注意,在您的代碼中,您還嘗試將食物型別(例如三明治)與口味(例如酸味)相匹配,反之,這可能是不可取的。這段代碼不這樣做。
def foodresults():
points = 0
sentences = {0: "It didn't like it very much...",
1: "You got a match, nice job! 1 point",
2: "Wow, it couldn't have enjoyed it more! 2 points",
}
for food in foods:
matches = sum(map(lambda x: x[0]==x[1], zip(favorites, food)))
points = matches
print(*food)
print(sentences[matches])
print(f'You got a total of {points} points!')
foodresults()
輸出:
salty pizza
It didn't like it very much...
sweet sandwiches
Wow, it couldn't have enjoyed it more! 2 points
sour sandwiches
You got a match, nice job! 1 point
You got a total of 3 points!
使用的輸入:
favorites = ('sweet', 'sandwiches')
foods = (('salty', 'pizza'),
('sweet', 'sandwiches'),
('sour', 'sandwiches'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/401015.html
