首页 > 解决方案 > 如何解决嵌套列表的循环问题?

问题描述

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

我已经阅读了有关嵌套列表和循环的所有内容,但无法找到我需要的内容。我已经取出了嵌套的 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.")

我只希望它查找用户输入,即“google”。输出底部的第三行说“登录不存在”,这是“雅虎”,不认为这应该在这里,但不确定。只需要一点解释或方向。

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

谢谢!

标签: pythonpython-3.x

解决方案


打印数据库对您的问题无关紧要。

发生的事情是,如果您查看此代码:

        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.")

推荐阅读