简体   繁体   English

将不同的值附加到循环结果仅在最后一个值的列表中

[英]Appending varying values to loop results in list of last value only

I am simulating a position moving randomly and want to create a list of the position. I create a start position randomly and then add steps of random size to this start position:我正在模拟一个随机移动的 position,并希望创建一个 position 的列表。我随机创建一个开始 position,然后向这个开始 position 添加随机大小的步长:

import numpy as np

pos_range=1E-6
position=pos_range*np.random.rand(2)

steps=10
step_size=20E-9;

position_list=[]

for i in range(0,steps):
    step=step_size*np.random.rand(2)
    position+=step
    print(position)
    position_list.append(position)

The result of the print is打印的结果是

[6.47220682e-07 2.84186976e-07]
[6.48019947e-07 2.89315337e-07]
[6.50324286e-07 2.96818080e-07]
[6.64316483e-07 3.10052685e-07]
[6.79662022e-07 3.20408865e-07]
[6.85052985e-07 3.31529075e-07]
[6.97773479e-07 3.45764518e-07]
[7.11152822e-07 3.46809336e-07]
[7.14484731e-07 3.54165996e-07]
[7.20412104e-07 3.58339358e-07]

which is my desired result.这是我想要的结果。 But position_list only contains the same data of the last position value in all rows:但是 position_list 只包含所有行中最后一个 position 值的相同数据:

    position_list
array([[7.20412104e-07, 3.58339358e-07],
       [7.20412104e-07, 3.58339358e-07],
       [7.20412104e-07, 3.58339358e-07],
       [7.20412104e-07, 3.58339358e-07],
       [7.20412104e-07, 3.58339358e-07],
       [7.20412104e-07, 3.58339358e-07],
       [7.20412104e-07, 3.58339358e-07],
       [7.20412104e-07, 3.58339358e-07],
       [7.20412104e-07, 3.58339358e-07],
       [7.20412104e-07, 3.58339358e-07]])

I suspect it has something to with how the numpy array is stored in memory or the mixture of lists and numpy array.我怀疑它与 numpy 数组如何存储在 memory 或列表和 numpy 数组的混合中有关。 All the workarounds that I tried are tedious and I am interested why this code does not work as intended.我尝试过的所有解决方法都很乏味,而且我很想知道为什么这段代码不能按预期工作。

Change改变

position_list.append(position)

To

position_list.append(list(position))

position += step modifies position in place. position += step修改position到位。 You are appending the same object to position_list over and over again.您一遍又一遍地将相同的 object 附加到position_list

We can confirm this by looking at the set of unique object ids in position_list .我们可以通过查看position_list中唯一的 object id 集合来确认这一点。

>>> set(map(id, position_list))
{1637236197296}

There is an easy fix.有一个简单的解决方法。 Change position += step to position = position + step . position += step更改为position = position + step This avoids calling numpy.ndarray.__iadd__ .这避免调用numpy.ndarray.__iadd__

Also see Is i = i + n truly the same as i += n?另见Is i = i + n truly the same as i += n?

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

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