Answer the question
In order to leave comments, you need to log in
How to change the value of an array element by substituting some variable as the index of that element in the array?
There is a certain unchanging array of numbers that needs to be output to the console after some operations on it. The operations themselves are changing 1 of the array elements to something else depending on some conditions (I will not specify, because this is a little different). The trick is that the index of the changing element itself changes from time to time, i.e. you need to change elements of different depth in the array. I find the index itself through the definition. a function that returns something like this: "[1][5][0][4][1]" (it's str)
Some code :
array1 = [0, 1, 5 [5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0, 0, 0, 0]] #какой-то изначальный многомерный массив
def some_way(arr): #возвращает "путь" к 1 (допустим рандомный) из элементов передаваемого в формате str
some code
return way_to_some_element
path = some_way(array1)
array path = 5 #равносильно с array[5][0][что-то там-то] = 5 (значения в скобках могут изменяться в зависимости от каких-нибудь параметров функции)
print(array)
Answer the question
In order to leave comments, you need to log in
def change(arr, indexes, value):
head, tail = indexes[:-1], indexes[-1]
for i in head:
arr = arr[i]
arr[tail] = value
>>> arr = [0, 1, 5, [5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0, 0, 0, 0]]
>>> change(arr, [3, 1, 0], 999)
>>> arr
[0, 1, 5, [5, [999, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0, 0, 0, 0]]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question