python中字符串的复杂迭代

时间:2017-05-26 18:34:19

标签: python python-3.x

此代码的目的是通过用户输入检查,检查是否有任何单词与字典上的单词匹配,然后给出一个与第一个匹配单词相关的响应,如果没有回复" I我好奇告诉我更多"。我的问题是,我无法遍历列表并打印单个响应。

def main():
    bank = {"crashed":"Are the drivers up to date?","blue":"Ah, the blue screen of death. And then what happened?","hacked":"You should consider installing anti-virus software.","bluetooth":"Have you tried mouthwash?", "windows":"Ah, I think I see your problem. What version?","apple":"You do mean the computer kind?","spam":"You should see if your mail client can filter messages.","connection":"Contact Telkom."}

def welcome():
    print('Welcome to the automated technical support system.')
    print('Please describe your problem:')

def get_input():
    return input().lower().split()
def mainly():
    welcome()    
    query = get_input()

    while (not query=='quit'):
        for word in query:
            pass
            if word in bank:
                print(bank[word])


            elif not(word=="quit"):
                print("Curious, tell me more.")


        query = get_input()
mainly()
if __name__=="__main__":
    main()

1 个答案:

答案 0 :(得分:1)

在您的代码中,几乎没有错误。第一个,当你启动脚本时,你运行main来加载一个本地的'bank',它不存在于函数之外。当函数结束时,它“主要”运行但不记得字典。

第二个,当你使用一个字典结构时,你不需要循环通过并检查所有元素1乘1.您可以改为使用函数dict.get

我可以向你提出这个解决方案:

def welcome():
    print('Welcome to the automated technical support system.')
    print('Please describe your problem:')

def get_input():
    return input().lower().split()

def main():
    bank = {"crashed": "Are the drivers up to date?", ...}
    welcome()
    query = get_input()

    while query != 'quit':
        if bank.get(query, None) is not None:
            print(bank[query])
        else:
            print("doesn't exist")
        query = get_input()

    print("Curious, tell me more.") # will be triggered only when you are out of the loop

if __name__=="__main__":
    main()

在这种情况下,如果单词存在, bank.get(查询,无)将返回句子,否则返回None。

您还可以将其简化为:

while query != 'quit':
    sentence = bank.get(query, "doesn't exist")
    print(bank[query])
    query = get_input()

这是因为如果它存在,则句子=您要显示的内容,如果不存在,则会显示您想要的错误消息

我希望它有所帮助,