I am looking for a nicer solution for changing a specific item in a nested list of unknown and varying depth.
Say, I have a list lst = ['a', 'b', [['c'], ['d', ['e', 'f']]] and I want to change the 'e' to an 'x'.
I could do this by simply hard coding:
lst[2][1][1][0] = 'x'
But I'd have to use an unknown number of indices to change different items. Changing the 'c', e.g., would only require 3 indices.
To make it a bit more dynamic I've already written a function that returns the wanted indices of a certain item, in this case indices = get_indices('e', lst) would return the list [2, 1, 1, 0]
So my current solution is the following function:
def set_element(lst, index, value):
levels = len(index)
if levels == 1:
lst[index[0]] = value
elif levels == 2:
lst[index[0]][index[1]] = value
elif levels == 3:
lst[index[0]][index[1]][index[2]] = value
elif levels == 4:
lst[index[0]][index[1]][index[2]][index[3]] = value
elif levels == 5:
lst[index[0]][index[1]][index[2]][index[3]][index[4]] = value
elif levels == 6:
lst[index[0]][index[1]][index[2]][index[3]][index[4]][index[5]] = value
else:
return False
return True
Calling set_element(lst, indices, 'x') would do the trick.
But ... frankly ... I'm not quite happy with this solution, there has to be a smoother, pythonic way to achieve this. I'm probably missing something.
Can anybody think of an even more dynamic way where I don't have to predefine the maximum number of possible levels?
EDIT:
In the above example I've got the indices from the list I'd like to alter, which makes the method seem a bit overly complicated. In my specific case, however, I actually need to use the indices of an item to change another item in a different list of the very same structure.
So I have to insist on using the list of indices.
recursion. Googling it will get you far since your case is a very typical one.