Repetition for calling variables

Asked

Viewed 365 times

1

I have four variables [t1, t2, T3, T4], and each of them was defined as a string previously.

t1 = 'A vida vai ficando cada vez mais dura perto do topo.'
t2 = 'A moralidade é a melhor de todas as regras para orientar a humanidade.'
t3 = 'Aquilo que se faz por amor está sempre além do bem e do mal.'
t4 = 'Torna-te aquilo que és.'

If later in the code, I want to call each of these variables at once, I thought I’d do it this way:

for i in range(1,5):
   print(ti)

Thus, i would be replaced by numbers 1 to 4 and then call t1, t2, T3, T4 subsequently. Obviously, this method does not work. In fact it is possible to create a list of the texts and then do:

lista = [t1, t2, t3, t4]
for i in range(1,5):
   print(lista[i])

But it becomes antipratic to create a list when the number of variables is too high. My question is: is there any way to call multiple variables previously defined at once, how it would work in the above idealized 'for' repetition?

4 answers

2

One option is to use Dict comprehensions. Change the range value and increase the number of variables:

d = {'f' + str(i): 0 for i in range(5)}

Produces the following output:

{'f0': 0, 'f1': 0, 'f2': 0, 'f3': 0, 'f4': 0}

And to visualize:

for k, v in d.items():
    print(k, v)

Produces:

f0 0
f1 0
f2 0
f3 0
f4 0
  • Thanks for the help, but I rewrote my question to better express what I wanted.

2


In Python, in general, when you want to use _names_das_variables as variables themselves, the recommendation is to use a dictionary.

That is, instead of having "F1, F2, F3, F4", you could have a dictionary f with the keys 1, 2, 3 ,4.

But of course there are other ways - in case you just want to avoid having to repeat 4 times the same line of code. What you’re not taking into account is that the for Python always traverses sequences, and there are several forms of sequences - not just the numerical sequence returned by range.

In case, all you need is:

for var in (f1, f2, f3, f4):
    print(var)

Done: you create a local tuple-like sequence with the desired variables, and each tuple’s elm is associated with the variable of the for - and you avoid having to repeat the print 4 times.

DON’T DO SO But I’m going to include for reference purposes: although you shouldn’t do that: Python variables themselves are stored internally in dictionary-like structures. Then it is possible to access variables programmatically by name by accessing these dictionaries that are returned by calling the internal functions globals() and locals(), respectively for global and local variables.

for i in range(1, 5):
    print(globals()[f"f{i}"])
  • Thanks for the help, but I rewrote my question to better express what I wanted.

  • for many variables: use a dictionary as explained in the answer. Variables should be few and with a meaning within the context- if your variables have a name that must be accessed as given, as is what Voce wants to do, a dictionary is what you need. Note that although I have reiterated this several times, if you really want to insist on keeping variables with a "hardcoded" name, you do not want to create a list with them, and want to iterate on them, you can use the dictionary of globals or of locals as indicated in the last part-session of the reply.

1

I don’t know if I fully understand, but here’s a possible answer to your problem: If you have a list, for example:

lista = [f1,f2,f3,f4]

You can use the list directly in for:

for i in lista:
    print(i)

the exit will be:

f1
f2
f3
f4

if you want the same result, but with the counter, do it:

for cont, i in enumerate(lista):
    print(cont)
    print(i)

the result will be:

0
1
2
3
f1
f2
f3
f4

Thus, we can solve your problem using one of these methods, cited above. If you want to create a vector with numbers, do:

lista2 = [] #lista vazia
for i in range(5):
    lista2.append(i)
    print(lista2)

The result will be:

[0,1,2,3,4]

I hope I’ve helped, if it hasn’t been answered, please rewrite your question. vlw!

1

I’m not sure I understand your doubt, but from what I understand you could use a dictionary this way:

d = {'f1':1,'f2':2,'f3':3,'f4':4}
for x in range(1,5):
    print('{0} => {1}'.format('f'+str(x), d['f'+str(x)]))

and print according to your will. When adding new values you could do:

d['f'+str(int(max(d.keys())[1])+1)] = input()

Browser other questions tagged

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