[英]Indexing and slicing a multi-dimensional list
假設我有一個類似於任意維度的 ND 數組(讓ndim
是維度數)和一個len(indexes) == ndim
的元組indexes
的嵌套列表( ndlist
)。 如果ndlist
是一個 ND 數組,我可以執行以下操作:
ndlist[indexes] = (some object)
列表的等價物是什么? 請注意, ndim
是任意的,所以我不能像這樣對其進行硬編碼:
ndlist[indexes[0]][indexes[1]]... = (some object)
這是ndim == 3的示例:
ndlist = [[[10, 10], [10, 10]],[[10, 10], [10, 10]]] % 3-D (2x2x2) 列表,所有元素等於 10
當我事先知道ndim 時,我可以像這樣編輯ndlist的 (0,0,0) 元素:
ndlist[0][0][0] = 11 % 從 10 到 11 的變化需要 3 [0] 秒
現在假設 ndims == 4(4 維列表)。 編輯 ndlist 的 (0,0,0,0) 元素需要這樣的東西:
ndlist[0][0][0][0] = 11 % 更改為 11 需要 4 [0] 秒
對於任意 ndim:
ndlist[0][0][0]...[0] = 11 %change 到 11 需要 ndim [0]s 順序
如您所見,對於預先不知道 ndim 的一般情況,我無法以這種方式索引列表,因為它需要鍵入與 ndim 一樣多的 [0]。
如果我有一個這樣的數組而不是列表:
ndarray = np.array(ndlist)
訪問 (0, 0, 0, ... ,0) 不會成為問題,因為我可以使用元組同時索引所有維度,如下所示:
% 3d 案例
索引 = (0,0,0)
ndarray[索引]
% 4d 案例
索引 = (0,0,0,0)
ndarray[索引]
% 案例
索引 = (0, 0, 0, ... ,0) % 我可以用代碼生成這個
ndarray[索引] = 11
有沒有辦法用這樣的單個元組索引列表? 更好的是,元組可以保存切片而不是索引嗎? 例如數組也允許這樣做:
ndarray[ 0:2 , 0, 0] = np.array([0, 0])
我的問題找到的唯一解決方案是使用遞歸一次索引一個維度。 有更好的解決方案嗎? 謝謝!
現在我明白了這個問題。 如果您願意擁有一個對您來說很容易的函數 donig。 否則,您需要創建自己的列表類型。
您將需要一個函數,它接受一個列表和n
(未知)個元素。 n
意味着您將需要*argv
該函數將獲取列表並獲取n
( argv
) 中的第i
個元素。
def get_element(the_list, *argv):
sub_list = the_list.copy()
for i in argv:
sub_list = sub_list[i]
return sub_list
注意:該函數復制原始list
以確保它沒有被更改。
注意:您還需要處理index out of range
錯誤。 現在它會引發TypeError: 'blabla' object is not subscriptable
。
在這里,您將創建一個具有任何名稱的類(讓我們使用TypedList
),它繼承自list
並覆蓋__getitem__
方法。
class TypedList(list):
def __getitem__(self, keys):
sub_list = self.copy()
for i in keys:
sub_list = sub_list[i]
return sub_list
if __name__ == '__main__':
ndlist = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
lst = TypedList(ndlist)
print(lst[1, 1, 0, 2])
在這里,您還需要處理index out of range
錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.