我有这个代码:
import random
greetings_commands = ('hello', 'hi', 'hey')
compliment_commands = (' you look great', 'you are so good', 'you are amazing')
greetings_responses = ['hi sir', 'hello sir', 'hey boss']
compliment_responses = ['so as you sir', 'thanks, and you look beautiful', 'thanks sir']
commands_list = {greetings_commands: greetings_responses, compliment_commands: compliment_responses}
while True:
user_input = input('Enter your message: ') # user input or command or questions
if user_input in commands_list: # check if user_input in the commands dictionary keys
response = random.choice(commands_list[user_input]) # choose randomly from the resonpses list
print(response) # show the answer
现在,不满足if user_input in commands_list
条件,并且不打印response
。
如果在用于字典键的元组中的任何中找到user_input
,如何从字典中的相应值中选择response
?
遍历字典的键和值,在找到包含用户输入的键后选择响应。
while True:
user_input = input('Enter your message: ') # user input or command or questions
for commands, responses in commands_list.items():
if user_input in commands:
response = random.choice(responses) # choose randomly from the resonpses list
print(response)
break
或者扩展commands_list
,使每个键都是一个命令,以使查找更容易:
commands_list = {command: responses
for commands, responses in commands_list.items()
for command in commands}
然后您当前的代码就可以工作了。