我对全局变量没有用处,也从来没有明确地定义过一个,但我似乎在我的代码中有一个。你能帮我把它变成当地的吗?为什么我的(本地)变量的行为像一个全局变量?
def algo(X): # randomized algorithm
while len(X)>2:
# do a bunch of things to nested list X
print(X)
# tracing: output is the same every time, where it shouldn't be.
return len(X[1][1])
def find_min(X): # iterate algo() multiple times to find minimum
m = float('inf')
for i in some_range:
new = algo(X)
m = min(m, new)
return m
X = [[[..], [...]],
[[..], [...]],
[[..], [...]]]
print(find_min(X))
print(X)
# same value as inside the algo() call, even though it shouldn't be affected.
X似乎表现得像一个全局变量。随机算法algo()
在第一次调用时只执行一次,因为X保留其更改后的值,因此它永远不会在while
循环内执行。 find_min
中迭代的目的因此被击败。
我是新来的蟒蛇,甚至更新的论坛,所以让我知道如果我需要澄清我的问题。谢谢。
更新非常感谢迄今为止所有的答案。我几乎了解它,除了我之前做过这样的事情,结果更加快乐。你能解释为什么下面的代码不同吗?
def qsort(X):
for ...
# recursively sort X in place
count+=1 # count number of operations
return X, count
X = [ , , , ]
Y, count = qsort(X)
print(Y) # sorted
print(X) # original, unsorted.
谢谢。
更新II为了回答我自己的第二个问题,差异似乎是在第一个代码(未显示)中使用列表方法,而在第二个代码中缺少它。
谢谢。这很好。 – bongbang 2012-07-09 05:17:25