简体   繁体   中英

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 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. I have also tried to use extend instead of append method. The append method packed all ndarray as one array and does not allow me to access each individual ndarray stored in cropped_fishim . The extend method does store ndarray separately, but cropped_fishim[index] would only access the index th col array. 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; 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; you can just loop over 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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