Q
Q
qqqqqqqqqqqa2021-11-29 00:03:46
Python
qqqqqqqqqqqa, 2021-11-29 00:03:46

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)


You yourself, I think, understand that it is impossible to designate an element of an array (or list), and yes, I have already tried something like int(path) etc., but it does not seem to work that way. Please tell me how to implement what I want to do? If you don't understand something - ask
(I tried to google)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AWEme, 2021-11-29
@qqqqqqqqqqqa

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]]

arr - reference to an array with subarrays
indexes - array of indices
value - value to be inserted into the list

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question