Python全局列表

Nat*_*han 1 python list globals

我正在学习python,并且遇到了全局变量/列表的问题.我正在编写河内程序的基本手册,这是目前的程序:

pilar1 = [5,4,3,2,1,0]
pilar2 = [0,0,0,0,0,0]
pilar3 = [0,0,0,0,0,0]

def tower_of_hanoi():

    global pillar1
    global pillar2
    global pillar3

    print_info()

def print_info():

    global pillar1
    global pillar2
    global pillar3

    for i in range(4,-1,-1):
        print(pillar1[i], " ", pillar2[i], " ", pillar3[i])
Run Code Online (Sandbox Code Playgroud)

我尝试了一些变化,但每次我收到错误"NameError:全局名称'pillar1'未定义".

在此设置中处理全局列表的最佳方法是什么?如果可能的话,我更愿意只使用一个源文件.谢谢!

mgi*_*son 10

这是因为你已经"声明"了它pilar1,而不是pillar1


小智 6

你遇到的问题pilar不一样pillar.解决之后,您将不再需要global声明:

pilar1 = [5,4,3,2,1,0]
pilar2 = [0,0,0,0,0,0]
pilar3 = [0,0,0,0,0,0]

def tower_of_hanoi():    
    print_info()

def print_info():    
    for i in range(4,-1,-1):
        print(pillar1[i], " ", pillar2[i], " ", pillar3[i])
Run Code Online (Sandbox Code Playgroud)

只有在非全局范围内分配全局变量时才需要使用global,例如函数定义:

# global variable, can be used anywhere within the file since it's
# declared in the global scope
my_int = 5

def init_list():
    # global variable, can be used anywhere within the file after
    # init_list gets called, since it's declared with "global" keyword
    global my_list
    my_list = [1, 2, 3]

def my_function():
    # local variable, can be used only within my_function's scope
    my_str = "hello"

    # init's global "my_list" variable here, which can then be used anywhere
    init_list()
    my_list.append(5)

my_function()
print(my_list)
Run Code Online (Sandbox Code Playgroud)

但是,您不应该使用全局变量,而是使用函数参数来传递值.

  • 这个有一个小问题,*define* 意味着只有当你创建一个新的全局变量时,这不是真的,这是对需要 `global` 关键字的全局变量的 *赋值*。 (2认同)