简体   繁体   English

将新变量分配给 Python 中的 arrays 列表

[英]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 .我正在尝试将新变量K分配给 arrays Path列表。 However, I don't know how to append a list of arrays.但是,我不知道如何在 append 列表中列出 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当前的 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 ])]

The expected output is预期的 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 ])]

I think the question is about copying!我认为问题是关于复制!

The answer isdeepcopy :答案是deepcopy

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 = 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 .如果您将Path复制到K中,则更改K中的项目不会更改Path

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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