python - 无故改变列表值的函数

标签 python python-2.7

我对我为 python 编写的这个函数感到震惊。我观察到,在较低的 while 中,它更改了列表 vctor 中的值,即使该列表在函数中没有被触及。我已经传递了对 (10, [1,3,5,7,10]) 并将列表 vctor 更改为 [1,3 ,5,8,10]。对此有解释吗?

def siguiente(k,vctor):
    l = len(vctor)
    vctorsig = vctor
    i = l-1
    while i>= 0:    
        if vctorsig[i] <= k - l + i: 
            j=i
            while j<=l-1:
                print vctor
                vctorsig[j] = vctor[i]+j-i+1
                j=j+1
            i = -1
        else:
            i = i-1
    return vctorsig    

最佳答案

当您执行 vctorsig = vctor 时,您正在使 vctorsig 成为对 vctor 所引用列表的引用,因此当您修改它时,您修改原始列表。

如果你想在那里复制列表,你可以简单地做 vctorsig = list(vctor)

关于python - 无故改变列表值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13205618/

相关文章:

python - 数据库变量的语法错误 (MySQL/Python)

python - Python 中的魔术方法(dunders)与 C++ 中的运算符重载相同吗?

python - 如何使用 pandas Python 将字符串拆分为数据框中的几列?

python - docker python simplehhtpserver 不工作

python - 如何使用 pip 1.5(在 Python 上)安装和升级外部托管的包存储库?

python - 为什么进度条总是卡在99%?

python - 将字节转换为 Int 时出错 (Python 2.7)

python - 如何在 Python 上逐行从 sys.stdin 获取前 N 行

python-2.7 - HTTP Basic Auth 的 Python mechanize 实现

python - Python 2.7 中的 `id` 函数,`is` 运算符、对象标识和用户定义的方法