Python:每个项目匹配问题的字典

问题描述 投票:-2回答:1

我正在尝试在Hackerank的字典中查找与键对应的值

我试图打印出每个要调试的进程,但发现该进程的运行完全符合我的预期,但是结果确实很奇怪。我的输出显示该语句确实读取了正确的名称“ harry”,但在我的词典中找不到“ harry”。有人可以给我一些想法吗,谢谢!

这是我的代码:

if __name__=='__main__':
    n = int(input()) #input how many pairs of name-phone in this phonebook
    d = dict()

    for count in range(n):
        name, phone = input().split()
        d[name] = phone
    print(d)

    while True:
        search_phone = input() #input the name
        print('enter new name') #debug

        for name, phone in d.items():
            if search_phone == name :
                print(name + '=' + phone)
                print(search_phone + ' bingle, continue to enter another name')
                break

            elif search_phone != name:
                print('Not found')
                print(search_phone + ' no match, continue to enter another name')
                break

示例输入为:

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

预期输出:

sam=99912222
Not found
harry=1229993

我的输出是:

{'sam': '99912222', 'tom': '11122222', 'harry': '12299933'}    
enter new name
sam=99912222
sam bingle, continue to enter another name
enter new name
Not found
edward no match, continue to enter another name
enter new name
Not found
harry no match, continue to enter another name 
###my question is why it did read harry but goes to no match?
python dictionary if-statement break
1个回答
0
投票

发生这种情况,因为您将break放在了您的else语句中。因此,代码将在第一个循环处中断,并且无法获得d中的下一个项目。因此,您必须消除else语句中的中断。

但是我们有一个新问题,在每个循环中,如果search_phone != name,将执行else语句。因此,我们已经解决了这个问题。您可以尝试这个(对不起,英语不好)

 while True:
        search_phone = input() #input the name
        print('enter new name') #debug
        valid = False

        for name, phone in d.items():
            if search_phone == name :
                print(name + '=' + phone)
                print(search_phone + ' bingle, continue to enter another name')
                valid = True
                break

        if not valid:
            print('name:', name)
            print('Not found')
            print(search_phone + ' no match, continue to enter another name')
© www.soinside.com 2019 - 2024. All rights reserved.