Python 向列表添加元素(追加)

0 投票
2 回答
931 浏览
提问于 2025-04-17 13:57

我在使用append函数时遇到了问题。它就是不往列表里添加单词。我想做的是一个账户登录的功能,可以添加新的账户,以便在登录时使用。这只是一个示例脚本,但原理是一样的。我想把一个新单词添加到我的映射中(比如:Guido),然后我可以用这个单词“guido”让我的程序打印出“yay”。

mapp = ["example"]



example1 = raw_input("Enter Username: ")
if example1 in mapp:
    print "yay"
else:
    print ("Forgot Username eh?")
    example = raw_input("Enter New Username: ")
    if example not in mapp:
        mapp.append(example)

如果有人能帮忙,那就太感谢了。

2 个回答

0

它确实会把单词加到列表里(只加一个单词,因为你只做了一次)。在最后加上 print mapp,你就能看到结果了。

1

只需在你的脚本最后加上这一行,就能看到它确实在运行。(我编辑了一下,添加了一个while循环,这样程序就会一直运行下去)。

mapp = ["example"]


while True:
    example1 = raw_input("Enter Username: ")
    if example1 in mapp:
        print "yay"
    else:
        print ("Forgot Username eh?")
        example = raw_input("Enter New Username: ")
        if example not in mapp:
            mapp.append(example)

    print mmap

撰写回答