Python修改不在函数内部的变量

标签 python function global-variables function-call

def center_to_origin(to_centered):
for j in range(to_centered.shape[1]):
    mean_x = 0
    mean_y = 0
    for i in range(to_centered.shape[0]):
        if i%2==0:
            mean_x = mean_x + np.mean(to_centered[i, j])
        else:
            mean_y = mean_y + np.mean(to_centered[i, j])
    mean_x = mean_x/(40)
    mean_y = mean_y/(40)
    for i in range(to_centered.shape[0]):
        if i%2==0:
            to_centered[i, j] = to_centered[i, j] - mean_x
        else:
            to_centered[i, j] = to_centered[i, j] - mean_y
return to_centered

我有上面的功能。我想调用这个函数而不让它改变我的变量。因此,我为此目的创建了一个临时变量。换句话说,我想将这个函数返回的变量存储到 temp 中。我将该函数称为,

temp = landmarks_per_tooth[index]
print(landmarks_per_tooth[index][:, 1])
temp = center_to_origin(landmarks_per_tooth[index])
print(landmarks_per_tooth[index][:, 1])

当然,在第一个打印中,我在控制台中看到了变量的值。但是,在第二次打印中,我看到变量的值已更改。我的控制台中的输出如下所示:

[1357.  669. 1348.  682. 1346.  698. 1345.  716. 1343.  732. 1341.  748.
 1339.  764. 1338.  780. 1338.  796. 1337.  812. 1335.  828. 1331.  842.
 1324.  858. 1320.  874. 1318.  890. 1317.  906. 1322.  922. 1328.  934.
 1337.  946. 1347.  954. 1359.  952. 1368.  944. 1378.  932. 1383.  914.
 1385.  900. 1385.  882. 1383.  868. 1382.  852. 1382.  836. 1382.  820.
 1384.  804. 1385.  792. 1385.  776. 1384.  760. 1383.  744. 1382.  728.
 1382.  712. 1380.  696. 1377.  682. 1368.  671.]


[  -0.7 -146.4   -9.7 -133.4  -11.7 -117.4  -12.7  -99.4  -14.7  -83.4
  -16.7  -67.4  -18.7  -51.4  -19.7  -35.4  -19.7  -19.4  -20.7   -3.4
  -22.7   12.6  -26.7   26.6  -33.7   42.6  -37.7   58.6  -39.7   74.6
  -40.7   90.6  -35.7  106.6  -29.7  118.6  -20.7  130.6  -10.7  138.6
    1.3  136.6   10.3  128.6   20.3  116.6   25.3   98.6   27.3   84.6
   27.3   66.6   25.3   52.6   24.3   36.6   24.3   20.6   24.3    4.6
   26.3  -11.4   27.3  -23.4   27.3  -39.4   26.3  -55.4   25.3  -71.4
   24.3  -87.4   24.3 -103.4   22.3 -119.4   19.3 -133.4   10.3 
-144.4]

有人可以帮忙吗?

最佳答案

temp 分配给数组的副本

temp = np.copy(landmarks_per_tooth[index])

关于Python修改不在函数内部的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50581063/

相关文章:

Python:递归:查找二叉树的叶子数

php - 我在哪里放置我的自定义类和函数在 Laravel 中

即使使用了 global 关键字,PHP 全局变量在函数内部也是未定义的

swift - 用户输入作为全局变量以显示来自不同 View 的文本

javascript - 从包含的 JS 文件访问全局变量

python - 无法将标准输出复制到 python 中的文件

通过全局公共(public) IP 地址连接的 Python 套接字

python - 无效凭据引发身份验证突变异常

python - 在Python中创建多个需要能够互相调用的函数

python - Python 和 Pandas 的问题 : Adding calculated column to dataframe that includes data from a function provides error