如何将 ndarray 附加到列表并从列表中访问每个存储的 ndarray?

How do I append ndarray to a list and access the each stored ndarray from the list?

我正在尝试创建一个列表来存储从我的 for 循环生成的所有 ndarray:

for index in range(len(fishim)):
    cropped_fishim = []
    cropped_image = crop_img(fishim[index], labeled)#call function here.
    cropped_fishim.append(cropped_image)

然后我想使用 cropped_fishim[index] 访问每个存储的 ndarray 以进行进一步处理。我也尝试使用 extend 而不是 append 方法。 append 方法将所有 ndarray 打包为一个数组,不允许我访问存储在 cropped_fishim 中的每个 ndarray。 extend 方法确实单独存储 ndarray,但 cropped_fishim[index] 只会访问第 indexth col 数组。任何帮助将不胜感激。

问题已解决。谢谢!

学到的简单技巧:

cropped_fishim = [None]*len(fishim)

for index in range(len(fishim)):
    cropped_image = crop_img(fishim[index], labeled)#call function here.
    cropped_fishim[index] = cropped_image

append是正确的;你的问题在上面一行:

for index in range(len(fishim)):
    cropped_fishim = []
    cropped_image = crop_img(fishim[index], labeled)#call function here.
    cropped_fishim.append(cropped_image)

每次循环,您将变量重置为 [],然后将新图像数组附加到该空列表。

因此,在循环结束时,您有一个只包含一件事的列表,即最后一个图像数组。

要解决这个问题,只需将赋值移动到循环之前,这样您只需执行一次而不是一遍又一遍:

cropped_fishim = []
for index in range(len(fishim)):
    cropped_image = crop_img(fishim[index], labeled)#call function here.
    cropped_fishim.append(cropped_image)

但是,一旦你完成了这个工作,你就可以简化它。

你几乎不需要——也不想——在 Python 中循环遍历 range(len(something));你可以循环 something:

cropped_fishim = []
for fishy in fishim:
    cropped_image = crop_img(fishy, labeled)#call function here.
    cropped_fishim.append(cropped_image)

然后,一旦你这样做了,这就是列表理解的模式,所以你可以选择将它折叠成一行:

cropped_fishim = [crop_img(fishy, labeled) for fishy in fishim]