Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

python - Method for indexing into a list by a number of dimensions

I am writing code that uses nested lists. My list structure is essentially 2 elements, but the second element comprises two individual elements and so on and so forth. The size of the list therefore grows as 2^n + 1. Anyway, for each recursion of a function I need to be able to access any given element at some 'depth'. Usually, this would be trivial as given,

list1 = [[0,1], [[1,2], [1,0]]]

the following code:

list1[1][1]

would return:

[1,0]

However, for an n dimensional nested list (I use the word 'dimension' fairly haphazardly given that this is a nested list and not an array) I would surely need to 'exponentiate' my [1] index in order to index into each progressively 'deeper' nested list. Is there a trivial way to do this?

Thanks in advance, your help is greatly appreciated.

question from:https://stackoverflow.com/questions/66055546/method-for-indexing-into-a-list-by-a-number-of-dimensions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use recursion:

def get(li, k):
    return get(li[1], k-1) if k > 0 else li

Or iteration:

def get(li, k):
    for _ in range(k):
        li = li[1]
    return li

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...