我遇到了一个Python 2.7的问题,令我疯狂。非常奇怪的Python变量范围行为
我正在向一些函数传递一个数组,并且尽管变量被认为是本地变量,但最终main变量的值被改变了。
我对Python有点新,但是这违背了我的任何常识。
任何想法我做错了什么?
def mutate(chromo):
# chooses random genes and mutates them randomly to 0 or 1
for gene in chromo:
for codon in gene:
for base in range(2):
codon[randint(0, len(codon)-1)] = randint(0, 1)
return chromo
def mate(chromo1, chromo2):
return mutate([choice(pair) for pair in zip(chromo1, chromo2)])
if __name__ == '__main__':
# top 3 is a multidimensional array with 3 levels (in here I put just 2 for simplicity)
top3 = [[1, 0], [0, 0], [1, 1]]
offspring = []
for item in top3:
offspring.append(mate(top3[0], item))
# after this, top3 is diferent from before the for cycle
UPDATE 因为Python经过参考,我一定要在使用前阵列FO一个真正的副本,所以队友功能必须改成:
import copy
def mate(chromo1, chromo2):
return mutate([choice(pair) for pair in zip(copy.deepcopy(chromo1), copy.deepcopy(chromo2))])
的可能的简短的回答是有在Python中没有“变量”,只有“名字”,这基本上意味着一切都是通过引用,甚至序列中的项目。 – 2011-12-31 00:56:45
是的,我现在改变了。谢谢:) – jbssm 2011-12-31 00:57:42
@jbssm:另外,请不要使用'from random import *'。出于充分的理由,这被认为是不好的做法 – 2011-12-31 00:59:50