簡體   English   中英

Python修改不在函數內部的變量

[英]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

我有上面的功能。 我想調用此函數而不讓它改變我的變量。 因此,我為此目的創建了一個臨時變量。 換句話說,我想將從此函數返回的變量存儲到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])

您應該使用copy實際創建變量的副本。

from copy import copy
temp = copy(landmarks_per_tooth[index])

我認為Chris_Rands的評論完全正確。 不清楚什么是landmarks_per_tooth 如果要將可變對象(例如列表)傳遞給函數,則可以在函數內部對其進行更改。 您應該傳遞一個不可變的對象(例如元組)或將對象的副本傳遞給該函數。

temp = center_to_origin(copy_of_landmarks)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM