为什么我们用枚举法把一个数组的值复制到另一个数组时,会出现乱码?[重复]

问题描述 投票:0回答:1

这是我的代码,注释说打印函数的输出。

def rotLeft(a, d):
    rotArray = a
    arraySize = len(a)

    print(a)#[1, 2, 3, 4, 5]

    for index, item in enumerate(a):
        print(index) # 0 1 2 3 4
        print(item) # 1 1 1 1 1
        rotArray[(index + 1) % arraySize] = item

    return rotArray

如果我把最后的for指令去掉,我们就可以得到正确的值。但如果我们主坦,不知为何确实会把我原来的一个数组搞乱。为什么会发生这种情况,在这种情况下有什么好的做法?

python arrays python-3.x list enumerate
1个回答
2
投票

rotArray 指的是 a因此,修改它可以修改 a.

你可以这样做。

rotArray = a.copy()
© www.soinside.com 2019 - 2024. All rights reserved.