【问题标题】:How do I append ndarray to a list and access the each stored ndarray from the list?如何将 ndarray 附加到列表并从列表中访问每个存储的 ndarray?
【发布时间】:2019-02-12 04:45:30
【问题描述】:

我正在尝试创建一个列表来存储从我的 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 数组。任何帮助将不胜感激。

【问题讨论】:

  • 旁注:当索引仅用于索引someseq 时,for index in range(len(someseq)): 是一种反模式。这段代码可以简化为 for fish in fishim: 并引用 fishim[index] 变为 fishfish 可以更改为更具描述性的内容;我是从有限的上下文中猜测的)。它更快、更清晰、更灵活(如果 fishim 是任何可迭代类型,它会继续工作,而不仅仅是像 listtuple 这样的序列)。

标签: python list multidimensional-array append numpy-ndarray


【解决方案1】:

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]

【讨论】:

    【解决方案2】:

    问题解决了。谢谢!

    学会了简单的技巧:

    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
    

    【讨论】:

    • 总的来说,用Nones 预分配list 被认为是不符合Python 的;重复appends 消除了调整与替换占位符值的循环不同步的风险。只需将空list 的创建移到循环体之外,原始代码就可以轻松修复,调整list 的大小并没有真正的好处。
    • 虽然这可行,但它确实不是一个好的解决方案。最好使用append,但要正确使用。
    • 非常感谢大家的大力投入!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2019-07-03
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多