Python全局列表

-1 投票
2 回答
22378 浏览
提问于 2025-04-17 13:14

我正在学习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])

我尝试了几种不同的方法,但每次都出现“NameError: global name 'pillar1' is not defined”的错误。

在这种情况下,处理全局列表的最佳方法是什么?如果可能的话,我希望只使用一个源文件。谢谢!

2 个回答

6

你遇到的问题是 pilarpillar 这两个词不一样。修正这个问题后,你就不需要再使用 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])

只有在你在一个非全局的地方,比如函数定义中,给一个全局变量赋值时,才需要用到 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)

不过,最好不要过多使用全局变量,应该使用函数参数来传递值。

13

这是因为你把它写成了 pilar1,而不是 pillar1

撰写回答