2015-04-01 54 views
2

我有一個多維列表F,它包含某種類型的元素。所以,如果例如等級是4,那麼F的元素可以通過諸如F[a][b][c][d]之類的東西來訪問。我想訪問F[a][b][c][d]。我的問題是我的排名將會改變,所以我不能只有F[L[0]][L[1]][L[2]][L[3]]Python:訪問多維列表的元素,給出一個索引列表

理想情況下,我希望能夠做到F[L]並獲得元素F[a][b][c][d]。我認爲這樣的事情可以用numpy來完成,但對於我使用的數組類型,numpy並不合適,所以我想用python列表來完成。

我怎麼能有類似上面的東西?

編輯:有關我想要實現的具體示例,請參閱Martijn答案中的演示。

+0

我知道我的問題看起來有點草率。我還沒有設法找到一種更好的表達方式。 – geo909 2015-04-01 16:14:45

+0

我也發現這:https://stackoverflow.com/questions/7789143/dynamic-access-of-multi-dimensional-python-array然而,它不是重複的,因爲它只談論numpy數組.. – geo909 2015-04-01 16:15:11

+3

你可以通過給出樣本輸入和預期輸出 – thefourtheye 2015-04-01 16:15:17

回答

7

可以使用reduce() function訪問連續元素:

from functools import reduce # forward compatibility 
import operator 

reduce(operator.getitem, indices, somelist) 

在Python 3 reduce被移到了functools模塊,但在Python 2.6和高達你可以隨時訪問該位置。

以上使用operator.getitem() function將每個索引應用於以前的結果(從somelist開始)。

演示:

>>> import operator 
>>> somelist = ['index0', ['index10', 'index11', ['index120', 'index121', ['index1220']]]] 
>>> indices = [1, 2, 2, 0] 
>>> reduce(operator.getitem, indices, somelist) 
'index1220' 
2

像這樣的事情?

def get_element(lst, indices): 
    if indices: 
     return get_element(lst[indices[0]], indices[1:]) 
    return lst 

測試:

get_element([[["element1"]], [["element2"]], "element3"], [2]) 
'element3' 
get_element([[["element1"]], [["element2"]], "element3"], [0, 0]) 
['element1'] 

或者,如果你想要一個迭代版本:

def get_element(lst, indices): 
    res = lst 
    for index in indices: 
     res = res[index] 
    return res 

測試:

get_element([[["element1"]], [["element2"]], "element3"], [1, 0]) 
['element2']