You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数修改外部变量求助:调用函数时避免原变量被修改

问题分析与解决方案

这个问题的核心原因是NumPy数组属于可变对象,函数传递的是数组的引用而非副本——也就是说,你的center_to_origin函数里直接操作的to_centered,其实和你传入的landmarks_per_tooth[index]指向同一块内存空间,所以函数里的赋值操作会直接修改原数组的数据。

解决方法有两种,你可以根据需求选择:

方法一:修改函数内部,操作副本而非原数组

在函数开头先创建输入数组的副本,后续所有操作都基于这个副本进行,最后返回副本。这样原数组完全不会被改动:

import numpy as np

def center_to_origin(to_centered):
    # 先创建输入数组的副本,避免修改原数据
    centered_copy = to_centered.copy()
    for j in range(centered_copy.shape[1]):
        mean_x = 0
        mean_y = 0
        for i in range(centered_copy.shape[0]):
            if i % 2 == 0:
                mean_x += np.mean(centered_copy[i, j])
            else:
                mean_y += np.mean(centered_copy[i, j])
        mean_x /= 40
        mean_y /= 40
        for i in range(centered_copy.shape[0]):
            if i % 2 == 0:
                centered_copy[i, j] -= mean_x
            else:
                centered_copy[i, j] -= mean_y
    return centered_copy

方法二:不修改函数,调用时传入数组副本

如果你不想改动函数本身,可以在调用函数的时候,传入原数组的副本,这样函数操作的就是副本,原数组不受影响:

temp = landmarks_per_tooth[index]
print(landmarks_per_tooth[index][:, 1])
# 传入副本而非原数组
temp = center_to_origin(landmarks_per_tooth[index].copy())
print(landmarks_per_tooth[index][:, 1])

验证效果

修改后再运行你的调用代码,两次打印的landmarks_per_tooth[index][:, 1]结果会完全一致,说明原变量没有被修改,所有的中心化操作都只作用在副本上。

内容的提问来源于stack exchange,提问作者Mehr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:49:29