非常奇怪的Python变量作用域行为

2024-06-02 14:01:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python2.7上遇到了一个让我发疯的问题。在

我将一个数组传递给一些函数,虽然这个变量被suposed为local,但最终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

更新 因为Python是通过引用传递的,所以在使用数组之前,我必须对数组进行真正的复制,因此mate函数必须更改为:

^{pr2}$

Tags: 函数inforreturnmaindef数组mate
3条回答

操作chromo,通过引用传递。因此这些变化是破坏性的。。。因此return也是一种无意义的(codongene,而{}在{})。我想你需要把你的chromos做一份(深)拷贝。在

您遇到的问题源于python中的数组和字典是通过引用传递的。这意味着,不是由def创建并在本地使用的新副本,而是在内存中获得指向数组的指针。。。在

x = [1,2,3,4]

def mystery(someArray):
     someArray.append(4)
     print someArray

mystery(x)
[1, 2, 3, 4, 4]

print x
[1, 2, 3, 4, 4]

试着换衣服

在后代.append(匹配(top3[0],项))到 后代.append(配合(top3[0][:],项[:]))

或使用list()函数

相关问题 更多 >