您能否解释在双端队列中奇怪的np.array内容的“更新”?

问题描述 投票:0回答:2

此代码似乎可以“更新”双端队列中的内容?例如

import numpy as np
from collections import deque

buffer = deque()
load = np.array([1])

for loop in range(5):     
    print(list(buffer))  
    print("   >>>>> load[0] = loop # .... ...")
    load[0] = loop
    print(list(buffer))              
    print("   >>>>> buffer.append ...")
    buffer.append([loop, load]) 

输出=

[]
   >>>>> load[0] = loop # .... ...
[]
   >>>>> buffer.append ...
[[0, array([0])]]
   >>>>> load[0] = loop # .... ...
[[0, array([1])]]
   >>>>> buffer.append ...
[[0, array([1])], [1, array([1])]]
   >>>>> load[0] = loop # .... ...
[[0, array([2])], [1, array([2])]]
   >>>>> buffer.append ...
[[0, array([2])], [1, array([2])], [2, array([2])]]
   >>>>> load[0] = loop # .... ...
[[0, array([3])], [1, array([3])], [2, array([3])]]
   >>>>> buffer.append ...
[[0, array([3])], [1, array([3])], [2, array([3])], [3, array([3])]]
   >>>>> load[0] = loop # .... ...
[[0, array([4])], [1, array([4])], [2, array([4])], [3, array([4])]]
   >>>>> buffer.append ...

...如您所见,当为数组分配新值时,双端队列中的数组内容会更新?

python arrays numpy deque
2个回答
0
投票

您的代码中只有一个load对象,双端队列的每个项目都引用了这个对象,并且只有一个。如果您希望它们有所不同,请在每个循环中创建一个新的循环:

import numpy as np
from collections import deque

buffer = deque()


for loop in range(5):     
    print(list(buffer))  
    print("   >>>>> load[0] = loop # .... ...")
    load = np.array([loop])
    print(list(buffer))              
    print("   >>>>> buffer.append ...")
    buffer.append([loop, load]) 

输出:

[]
   >>>>> load[0] = loop # .... ...
[]
   >>>>> buffer.append ...
[[0, array([0])]]
   >>>>> load[0] = loop # .... ...
[[0, array([0])]]
   >>>>> buffer.append ...
[[0, array([0])], [1, array([1])]]
   >>>>> load[0] = loop # .... ...
[[0, array([0])], [1, array([1])]]
   >>>>> buffer.append ...
[[0, array([0])], [1, array([1])], [2, array([2])]]
   >>>>> load[0] = loop # .... ...
[[0, array([0])], [1, array([1])], [2, array([2])]]
   >>>>> buffer.append ...
[[0, array([0])], [1, array([1])], [2, array([2])], [3, array([3])]]
   >>>>> load[0] = loop # .... ...
[[0, array([0])], [1, array([1])], [2, array([2])], [3, array([3])]]
   >>>>> buffer.append ...

0
投票

dequereference保留在单个列表中。附加到buffer的每个元素都指向相同的np.array,最初命名为load

© www.soinside.com 2019 - 2024. All rights reserved.