简体   繁体   中英

Assigning new variable to a list of arrays in Python

I am trying to assign a new variable K to a list of arrays Path . However, I don't know how to append a list of arrays. I present the current and expected outputs.

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])

The current output is

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

The expected output is

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

I think the question is about copying!

The answer isdeepcopy :

from copy import deepcopy
K = deepcopy(Path)

None of the following assignments works because changing items in K , changes items in Path :

K = Path
K = list(Path)
K = Path[:]

Because:

K[0][0] = np.random.rand()
print(K[0][0] == Path[0][0])
# True

If you make a deep copy of Path into K , changing items in K won't change Path .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM