我希望在代码上有一个'else'语句,使用'for'和'if'语句迭代通过列表来查找作为字典键的项

问题描述 投票:1回答:3

我正在使用'for'语句,然后使用'if'语句从列表中的列表中查找项目。我想要“好奇,告诉我更多”只打印一次。

以下是我希望该程序的工作方式:

input: i have a cat
output: Cats are the greatest animals in the world

Input:i do not like dogs 
Output: Dogs are boring

input:i love my pet
Output:Curious, tell me more

我目前的代码:

Dict_1 = {'cat':'Cats are the greatest animals in the world','dog':'Dogs are boring'}
query = 0
while (not query=='quit'):
     query = input().split()
     for i in query:
          if i in Dict_1:
               query = Dict_1[i]
               print(query)
          else:
               print('Curious, tell me more')
python python-3.x
3个回答
0
投票

使用另一个变量来存储答案,并在找到答案后退出循环:

Dict_1 = {'cat':'Cats are the greatest animals in the world','dog':'Dogs are boring'}
query = 0
while (not query=='quit'):
     query = input().split()
     ans = None
     for i in query:
          if i in Dict_1:
               ans = Dict_1[i]
               break
     if ans is None:
          print('Curious, tell me more')
     else:
          print(ans)

1
投票

有了query = input().split(),你就把query变成了一个列表。例如。如果用户输入cat dog,查询将是['cat','dog']

所以,不要检查query=='quit'(它永远不会是真的,因为query是一个列表而不是字符串),你应该检查查询是否包含'quit''quit' in query

如果你不想在用户退出时打印'Curious, tell me more',那么使用无限的while循环,并在读取'quit'时打破循环。

您可以使用set intersection:commands_found = set(Dict_1.keys()) & set(query)生成包含查询中找到的命令的集合

这是一个有效的实现:

Dict_1 = {'cat':'Cats are the greatest animals in the world','dog':'Dogs are boring'}
query = []
while True:
    query = input().split()
    if 'quit' in query:
        break
    commands_found = set(Dict_1.keys()) & set(query)
    if commands_found:
        for i in commands_found: print(Dict_1[i])
    else:
        print('Curious, tell me more')

请注意,我现在正在使用queryquery = []初始化为列表。输出:

I like my cat
Cats are the greatest animals in the world
I like my cat and dog
Cats are the greatest animals in the world
Dogs are boring
I like my racoon
Curious, tell me more
I want to quit

0
投票

如果你想只打印一次,你可以尝试在打印“好奇,告诉我更多”之后将变量设置为true。所以代码应该看起来像(基于glhr的答案)

Dict_1 = {'cat':'Cats are the greatest animals in the world','dog':'Dogs are boring'}
query = []
out = False
while not 'quit' in query:
    query = input().split()
    for i in query:
         if i in Dict_1:
             print(Dict_1[i])
         else:
             if not out:
                 print('Curious, tell me more')
                 out = True

如果您希望每次用户输入查询时重置此项,请将out = False移动到while循环中。

© www.soinside.com 2019 - 2024. All rights reserved.