Python:在函数内更改全局变量和全局列表元素

时间:2016-04-18 01:56:33

标签: python list global-variables python-3.3

问题

我的代码遇到了另一个问题。我正在制作一个程序,根据需要操纵全局变量的值。我正在研究如何在函数内部使用global来更改全局变量的值。任何帮助将非常感激。如果你愿意,你可以修改整个代码。再次,谢谢。

代码

verifier = 0
letters = ["A","B","C","D","E","F","G","H","I"]

if verifier == 0:
    letters = ["A","B","C","D","E","F","G","H","I"]
if verifier == 1:
    letters = newlist()

def newlist():
     numbers = ["0","1","2","3","4","5","6","7","8"]
     return animals

def main():
    global verifier
    # this should print ["A","B","C","D","E","F","G","H","I"]
    print(letters) 
    # global variable should be changed to 1
    verifier = 1 
    # this should print ["0","1","2","3","4","5","6","7","8"] now
    print(letters) 
main()

1 个答案:

答案 0 :(得分:1)

使用global变量:

verifier = 0

def newlist():
    if verifier == 0:
        return ["A","B","C","D","E","F","G","H","I"]
    elif verifier == 1:
        return ["0","1","2","3","4","5","6","7","8"]

print newlist()

def main():
    global verifier
    verifier = 1
main()

print newlist()

您的代码结构错误。你不会通过改变变量来实现任何目标。

它的变量声明:

verifier = 0
letters = ["A","B","C","D","E","F","G","H","I"]

在调用main之前,如果代码获胜的第一个if和second将只检查一次。另外 - 阅读elif

if verifier == 0:
    letters = ["A","B","C","D","E","F","G","H","I"]
elif verifier == 1:
    letters = newlist()

"字母"在main中,总是会["A","B","C","D","E","F","G","H","I"]。如果要修复代码,请参阅我的示例。 if仅执行了一次。无需重新启动文件,您将无法重新扫描。

在大多数情况下global不必使用 - 您只需将变量传递给函数参数:

def newlist(verifier):
    if verifier == 0:
        return ["A","B","C","D","E","F","G","H","I"]
    elif verifier == 1:
        return ["0","1","2","3","4","5","6","7","8"]

def main():
    print newlist(0)
    print newlist(1)
main()

特别是在这项任务上 - 甚至不需要使用这些功能:

letters = {
    0: ["A","B","C","D","E","F","G","H","I"],
    1: ["0","1","2","3","4","5","6","7","8"]
}

print letters.get(0, None)