简体   繁体   English

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

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

I'm trying to create a list that store all ndarrays generated from my for loop: 我正在尝试创建一个列表,该列表存储从我的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)

Then I want to use cropped_fishim[index] to access the each stored ndarray for further process. 然后,我想使用cropped_fishim[index]访问每个存储的ndarray以进行进一步处理。 I have also tried to use extend instead of append method. 我也尝试使用extend而不是append方法。 The append method packed all ndarray as one array and does not allow me to access each individual ndarray stored in cropped_fishim . append方法挤满所有ndarray作为一个数组,不允许我进入每一个人ndarray存储在cropped_fishim The extend method does store ndarray separately, but cropped_fishim[index] would only access the index th col array. ndarray方法确实将ndarray分开存储,但是cropped_fishim[index]将仅访问第index个col数组。 Any help would be appreciated. 任何帮助,将不胜感激。

Problem solved. 问题解决了。 Thanks! 谢谢!

easy trick learned: 简单的窍门:

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 is correct; append正确; your problem is in the line above it: 您的问题在上面的行中:

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

Each time through the loop, you reset the variable to [] , then append the new image array to that empty list. 每次循环时,都将变量重置为[] ,然后将新的图像数组附加到该空列表。

So, at the end of the loop, you have a list containing just one thing, the last image array. 因此,在循环结束时,您将获得一个列表,其中仅包含一件事,即最后一个图像数组。

To fix that, just move the assignment before the loop, so you only do it once instead of over and over: 要解决此问题,只需将分配移到循环之前,这样您只需执行一次即可,而不是一遍又一遍:

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

However, once you've got this working, you can simplify it. 但是,一旦完成此工作,就可以简化它。

You almost never need—or want—to loop over range(len(something)) in Python; 您几乎不需要-或想要-在Python中循环range(len(something)) you can just loop over something : 你能刚刚超过环路something

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

And then, once you've done that, this is exactly he pattern of a list comprehension, so you can optionally collapse it into one line: 然后,一旦完成此操作,这就是列表理解的模式,因此您可以选择将其折叠为一行:

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

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

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