如何解决嵌套列表的循环问题?

2024-04-28 20:02:53 发布

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

我在Python中有一个赋值,用户从嵌套列表中查找密码。我得到的大部分代码我只需要完成它。我的代码足以让我交作业,但我想解释一下我做错了什么。如果我选择“谷歌”,它是第二个在名单上

我已经阅读了所有我能找到的关于嵌套列表和循环的内容,但没有找到我需要的。我去掉了嵌套的for循环,它只会让事情变得更糟。我知道这是因为我不知道怎么做。你知道吗

        print("Which website do you want to lookup the password for?")
        for keyvalue in passwords:
            print(keyvalue[0])
        passwordToLookup = input()

        for i in passwords:
            if passwordToLookup in i:
                print("Your encrypted password is: " + i[1])
                print("Your unencrypted password is: " + passwordEncrypt(i[1], -16))
                break
            else:
                print("Login does not exist.")

我只想让它寻找用户输入,这是“谷歌”。第三行从底部的输出说“登录不存在”,这是为“雅虎”,不认为这应该在这里,但不确定。只是需要一点解释或指导。你知道吗

What would you like to do:
 1. Open password file
 2. Lookup a password
 3. Add a password
 4. Save password file
 5. Print the encrypted password list (for testing)
 6. Quit program
Please enter a number (1-4)
2
Which website do you want to lookup the password for?
yahoo
google
google
Login does not exist.
Your encrypted password is: CoIushujSetu
Your unencrypted password is: MySecretCode

谢谢!你知道吗


Tags: theto代码用户inyouwhich列表
1条回答
网友
1楼 · 发布于 2024-04-28 20:02:53

打印数据库对您的问题不重要。你知道吗

现在发生的事情是,如果你看这个代码:

        for i in passwords:
            if passwordToLookup in i:
                print("Your encrypted password is: " + i[1])
                print("Your unencrypted password is: " + passwordEncrypt(i[1], -16))
                break
            else:
                print("Login does not exist.")

您可以看到它将打印Login does not exist.,直到找到它为止。要修复它,您需要使用一个布尔值并等待循环完成,直到运行print("Login does not exist.")。所以,看起来是这样的:

        doesNotExist = True
        for i in passwords:
            if passwordToLookup in i:
                print("Your encrypted password is: " + i[1])
                print("Your unencrypted password is: " + passwordEncrypt(i[1], -16))
                doesNotExist = False
                break
        if doesNotExist:
            print ("Login does not exist.")

相关问题 更多 >