[英]Python modifies variables that is not inside the function
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
I have the function above. 我有上面的功能。 I want to call this function without let it alter my variable. 我想调用此函数而不让它改变我的变量。 So I create a temporary variable for this purpose. 因此,我为此目的创建了一个临时变量。 In other words, I want to store the returned variable from this function to temp. 换句话说,我想将从此函数返回的变量存储到temp。 I call the function as, 我称这个函数为
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])
In the first print, of course, I see the values for the variables in the console. 当然,在第一张图中,我会在控制台中看到变量的值。 However, in the second print I see that value of my variable has changed. 但是,在第二张图中,我看到变量的值已更改。 The output in my console looks like, 我的控制台中的输出如下所示:
[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]
Anyone can help? 有人可以帮忙吗?
将temp
分配给阵列的副本
temp = np.copy(landmarks_per_tooth[index])
You should use copy
to actually create a copy of the variable. 您应该使用copy
实际创建变量的副本。
from copy import copy
temp = copy(landmarks_per_tooth[index])
I think Chris_Rands comment is perfectly valid. 我认为Chris_Rands的评论完全正确。 It is not clear what is landmarks_per_tooth
? 不清楚什么是landmarks_per_tooth
? If you are passing a mutable object (eg list) to a function, it can be changed inplace inside the function. 如果要将可变对象(例如列表)传递给函数,则可以在函数内部对其进行更改。 You should either pass an immutable object (say tuple) or pass a copy of object to the function. 您应该传递一个不可变的对象(例如元组)或将对象的副本传递给该函数。
temp = center_to_origin(copy_of_landmarks)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.