Python的“append”函数

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

我在用append函数添加账户到映射时遇到了问题。

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(sana)

从这个脚本可以看到,如果我输入用户名“example”,程序就会打印“yay”。如果我输入错误的用户名,我可以创建一个新的“账户”,下次想让程序打印“yay”时可以使用这个账户。但是当我尝试添加新的“账户”时,它却不工作。我没有收到任何错误信息,但就是没有把新的“账户”添加到映射中。所以,有什么想法吗?

1 个回答

3

你没有把正确的变量添加到 mapp 里;你添加的是 sana,其实应该添加 example

if example not in mapp:
    mapp.append(example)

对于这个情况,你可以用 set 来代替:

mapp = {'example'}

# ...
if example1 in mapp:
    # ...
else:
    # ... 
    example = raw_input("Enter New Username: ")
    mapp.add(example)

撰写回答