Create objects with similar names with a for cycle in python

2

I want to create 24 matrices like this:

import numpy as np

tabla1 = np.empty((25*5,3 + 11))
tabla2 = np.empty((25*5,3 + 11))
.
.
.
tabla24 = np.empty((25*5,3 + 11))

To avoid having to write it 24 times, I thought about using a for cycle, but I do not know the proper syntax.

I tried this:

for i in range(1, 25):
    tabla{i} = np.empty((25*5,3 + 11))

But it's wrong.

What would be the right way to do it?

    
asked by Lucy_in_the_sky_with_diamonds 06.04.2017 в 00:21
source

2 answers

1

What you want to do is to use the exec function, in this example I think and initialized 25 objects whose name goes from variable1 to variable25:

for i in range(1,26):
    exec('variable{} = 0'.format(i))

Using your example

for i in range(1,26):
    exec('tabla{} = np.empty((25*5,3 + 11))'.format(i))

An important comment: exec is a potentially dangerous feature, particularly if the we use with sentences written by the user, we should limit its use to well-controlled cases.

Another slightly weirder way is to directly access the globals() or locals() , for example:

for i in range(1,26):
    globals()['tabla{}'.format(i)] = np.empty((25*5,3 + 11))
    
answered by 06.04.2017 / 04:16
source
3

in Python something can be repeated N times if it is in a list.

>>>['hola'] * 25 
# ['hola', 'hola', 'hola'....] como lo mostrado.

I could be useful at some point.

Now range creates Ranges from 0 to n, that is, range (1,25) will create a range from 1 to 24

As I believe what you occupy is something like this. Note that table [i] uses "[]" and not "{}" to access the list, a matrix at the end of the account is a list list.

tablas = dict() # Declaramos el diccionario
for i in range(0, 25):
    tablas['tabla'+str(i+1)] = np.empty((25*5,3 + 11))
tablas['tabla1'] # para mostrar lo guardado en tabla1

I hope that works for you.

    
answered by 06.04.2017 в 00:31