【问题标题】:Loop Nesting Issue, Items not Properly Referenced循环嵌套问题,未正确引用的项目
【发布时间】: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_ftchosen_ff 未定义。
  • 它们是在我遗漏的部分代码中定义的,是从列表中随机选择的。我应该把它包括在问题中吗?
  • 你应该包含一个minimal reproducible example
  • 不要使用名称object 作为python 关键字的变量

标签: python for-loop debugging tuples nested-loops


【解决方案1】:

您可以重构代码以使用单个循环和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'))

【讨论】:

    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2012-03-17
    • 2021-05-17
    • 2016-06-23
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多