簡體   English   中英

如何將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作為一個數組,不允許我進入每一個人ndarray存儲在cropped_fishim ndarray方法確實將ndarray分開存儲,但是cropped_fishim[index]將僅訪問第index個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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM