我正在努力编一本对狗有好有坏的食物的字典

2024-05-19 12:24:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在让它打印列表中每个项目的响应时遇到了一个问题,但是如果我去掉了负责的循环,我就无法检查用户输入,例如,如果他们输入“almond”,它会说它不知道,因为在我的列表中,它说的是“almonds”

这就是我对每个元素进行循环的原因,因此它将在元素中搜索单词,但循环打印出它无法找到答案几次(不必要!),然后是答案

我希望这是可以理解的,以下是我的代码:

good = ['bread','cashews','cheese','coconut']
bad = ['almonds','chocolate','cinnamon']
def check(food):
  for b,g in zip(bad,good):
    if food.lower() in g:
      print(f'Yes, dogs can eat {food}.')
      break
    elif food.lower() in b:
      print(f'No, dogs cannot eat {food}.')
      break
    else:
      print(f'{food} is not in my dictionary yet. My apologies.')

while True:
  f = str(input('What food would you like to check?: '))
  check(f)

Tags: 项目答案in元素列表foodchecklower
3条回答

您可以使用这种简单的pythonic方法并摆脱循环:

def check(food):
    if any(list(map(lambda g: food.lower() in g, (g for g in good)))):
        print(f'Yes, dogs can eat {food}.')
    elif any(list(map(lambda b: food.lower() in b, (b for b in bad)))):
        print(f'No, dogs cannot eat {food}.')
    else:
      print(f'{food} is not in my dictionary yet. My apologies.')

您需要分别循环浏览这两个列表:

good = ['bread','cashews','cheese','coconut']
bad = ['almonds','chocolate','cinnamon']

def check(food):
    for g in good:
        if food.lower() in g:
            print(f'Yes, dogs can eat {food}.')
            return None
    for b in bad:
        if food.lower() in b:
            print(f'No, dogs cannot eat {food}.')
            return None
    else:
        print(f'{food} is not in my dictionary yet. My apologies.')
        return None

while True:
    f = str(input('What food would you like to check?: '))
    check(f)

添加return语句非常重要,因此函数会在满足条件的地方停止,如果删除return语句,它将始终打印最后一行。(您也可以使用break,但我更喜欢return

您不需要zip()函数,并且需要一个return而不是break来结束函数。另外,我建议您添加一个退出条件,以便可以停止while循环

以下是我的建议:

good = ['bread','cashews','cheese','coconut']
bad = ['almonds','chocolate','cinnamon']

def check(food):
    if food.lower() in good:
        print(f'Yes, dogs can eat {food}.')
    elif food.lower() in bad:
        print(f'No, dogs cannot eat {food}.')
    else:
        print(f'{food} is not in my dictionary yet. My apologies.')
    return

while True:
    f = str(input('What food would you like to check?: '))
    if f == 'exit':
        break
    check(f)

输出:

What food would you like to check?: almond
almond is not in my dictionary yet. My apologies.
What food would you like to check?: almonds
No, dogs cannot eat almonds.
What food would you like to check?: exit

相关问题 更多 >