Reputation: 31
I have to do a code where I have to change some value in a for loop.
I have a list called listElement
.
I know the exact position of the item that I want to change which is store in a list. For instance [2,2,1]
called index
(which can also be for instance [3,2]
because my listElement
is composed of several lists of different sizes).
I would like to do something like this :listElement + index
which can create something like listElement[2][2][1]
(or listElement[3][2]
)
listElement = [ "a" , ["b","c"] , [["d"],["e","f"]] ]
tab = [ [2,1,0] , [0] ] # "e" and "a" position
element=""
for i in tab :
# recuperate the element at the position indicate by i
element = listElement[i]
Upvotes: 0
Views: 89
Reputation: 19405
You can just iterate on each index in the indices-list and get the next level each time:
def get_list_element(lst, indices):
element = lst
for index in indices:
element = element[index]
return element
The following program:
lst = [ "a", ["b", "c"], [["d"], ["e", "f"]] ]
indices_list = [[2,1,0] , [1], []]
for indices in indices_list:
print(get_list_element(lst, indices))
Will output:
e
['b', 'c']
['a', ['b', 'c'], [['d'], ['e', 'f']]]
Upvotes: 1
Reputation: 44013
Subclass ListElement
from list
and define method __add__
:
class ListElement(list):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __add__(self, l):
if not isinstance(l, (list, tuple)):
raise ValueError('value must be a list or tuple')
the_list = self
for inx in l:
if not isinstance(inx, int):
raise ValueError('the indices must be ints')
the_list = the_list.__getitem__(inx)
return the_list
listElement = ListElement([5, 6, [1, 2], [8, 9, [3, 8, 1]]])
print(listElement + [3, 2])
Prints:
[3, 8, 1]
Upvotes: 2
Reputation: 8298
You could do something like the following:
def recursiveAccess(list, elem):
if len(elem) == 1:
return list[elem[0]]
return recursiveAccess(list[elem[0]], elem[1:])
listElement = [ "a" , ["b","c"] , [["d"],["e","f"]] ]
tab = [ [2,1,0] , [0] ] # "e" and "a" position
for e in tab:
print(recursiveAccess(listElement, e))
# e
# a
Due to the fact you don't know in advance the access tree to an element of the list a recursive solution is in place. Notice that you should add some checks to validate that the input are always valid.
Upvotes: 2