将数组附加到列表会覆盖现有值

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

作为 python 的新手,我想用数组形式的图像填充列表。如果我添加元素,它们会覆盖现有值。如何将元素添加到列表中?

示例代码:

import numpy as np

ims = []
show_img= np.zeros([2,2,3],dtype=np.uint8)

for x in range(10):
    show_img.fill(x)
    ims.append(show_img)

print(show_img)

结果:

[[[9 9 9]
  [9 9 9]]

 [[9 9 9]
  [9 9 9]]]

预期将是一个包含所有元素的列表

python arrays append numpy-ndarray
1个回答
0
投票

正如评论所说,您不断修改和附加相同的数组。

无需预先创建数组,然后用不同的值填充它。使用

np.full()
一次性创建充满
x
值的数组。

ims = [np.full([2,2,3], x, dtype=np.uint8) for x in range(10)]
© www.soinside.com 2019 - 2024. All rights reserved.