How to create variable names during code execution?

Asked

Viewed 654 times

1

I need a little help.

During the execution of a code I get a list with x entries (the size of the list varies according to the input). Each entry in this list is a line array with a certain number of elements, not necessarily equal to each other.

To facilitate access during the rest of the code, I would like to name each entry in that list as a variable in the following scheme:

lista[0] = cD_x

lista[1] = cA_x

lista[2] = cA_(x-1)

lista[3] = cA_(x-2)

...

lista[x] = cA_1

As x varies with each execution I have no idea how to do that. Can someone give me a hand, please?

  • Can you explain why accessing a dynamically created variable will be better than accessing the index of a list?

1 answer

1

You don’t necessarily need to identify the arrays, and you probably shouldn’t, since they’re dynamic. Take the example:

tudo = [];

# Adicionando listas sem identificador em "tudo"
tudo.append([1, 2, 3, 4, 5, 6])
tudo.append(['banana', 'laranja', 'manga'])
tudo.append([0.456, 2.56, 0.0000004, 0.223, 33.33333])
tudo.append([True, True, False, True, False, False])

# A menos que você queira explicitamente identificar algo
# Aqui um lista tem o nome "especial"
especial = [4, 'Moscou', 32, 'Severino Raimundo', 0.5]
tudo.append(especial)

# E agora eis uma das formas de percorrer tudo o que existe
for lista in tudo:
    print()
    for elemento in lista:
        print(str(elemento))

# Podemos nos referir as listas por índice também
# Nesse caso você tem um "i" e um "j" nos quais "se agarrar"
for i in range(len(tudo)):
    print()
    print('LISTA ' + str(i) + ':')
    for j in range(len(tudo[i])):
        print('index[' + str(j) + '] = ' + str(tudo[i][j]))


Rewriting of the second loop according to Anderson Carlos Woss' suggestion:

# Podemos nos referir as listas por índice também
# Nesse caso você tem um "i" e um "j" nos quais "se agarrar"
for i, lista in enumerate(tudo):
    print()
    print('LISTA ' + str(i) + ':')
    for j, elemento in enumerate(lista):
        print('index[' + str(j) + '] = ' + str(elemento))
  • 1

    @Andersoncarloswoss I edited the answer by inserting your suggestion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.