[英]Assigning new variable to a list of arrays in Python
我正在嘗試將新變量K
分配給 arrays Path
列表。 但是,我不知道如何在 append 列表中列出 arrays。 我介紹了當前和預期的輸出。
import numpy as np
Path=[np.array([10. , 0.6382821834929432 , 0.5928417218382795 ,
0.5542698411479658 , 0.6677634679746701 , 0.8578897621707481 ,
0.6544597670890333 , 0.32706383813570833, 0.8966468940380192 ]),
np.array([10. , 0.6262206291648664 , 0.6413512609273813 ,
0.5417310533794202 , 0.763557281407787 , 0.580075670670837 ,
0.48048196888232686, 0.8537221497408958 , 0.35651700423205657,
0.9720842635477158 ])]
for i in range(0,2):
K=Path[i]
print([K])
當前的 output 是
[array([10. , 0.6382821834929432 , 0.5928417218382795 ,
0.5542698411479658 , 0.6677634679746701 , 0.8578897621707481 ,
0.6544597670890333 , 0.32706383813570833, 0.8966468940380192 ])]
[array([10. , 0.6262206291648664 , 0.6413512609273813 ,
0.5417310533794202 , 0.763557281407787 , 0.580075670670837 ,
0.48048196888232686, 0.8537221497408958 , 0.35651700423205657,
0.9720842635477158 ])]
預期的 output 是
[array([10. , 0.6382821834929432 , 0.5928417218382795 ,
0.5542698411479658 , 0.6677634679746701 , 0.8578897621707481 ,
0.6544597670890333 , 0.32706383813570833, 0.8966468940380192 ]),
array([10. , 0.6262206291648664 , 0.6413512609273813 ,
0.5417310533794202 , 0.763557281407787 , 0.580075670670837 ,
0.48048196888232686, 0.8537221497408958 , 0.35651700423205657,
0.9720842635477158 ])]
我認為問題是關於復制!
答案是deepcopy
:
from copy import deepcopy
K = deepcopy(Path)
以下分配均無效,因為更改K
中的項目會更改Path
中的項目:
K = Path
K = list(Path)
K = Path[:]
因為:
K[0][0] = np.random.rand()
print(K[0][0] == Path[0][0])
# True
如果您將Path
復制到K
中,則更改K
中的項目不會更改Path
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.