Looping using array name?

Question:

Im trying to loop over arrays with similar name, as such:

a0=[]
a1=[]
a2=[]
a3=[]
a4=[]

for k in range(len(mlac)):     # mlac.shape (17280, 5)
    for I in range(len(mlac[0])):
        'a%i'%I.append(mlac[k][I])
        # or : 'a{}'.format(I).append(mlac[k][I])

But both are considered strings on the loop and cannot append.

So for each iteration of ‘I’, we take the corresponding column of ‘mlac’ and add to the array ‘a’ of corresponding iteration.

Asked By: Lyu

||

Answers:

Trying to take a string and use it directly as a variable name is not a great idea.

If you’re allowed to change those arrays, you should change them to a list of lists or a dictionary. If not, you can load those existing arrays into another data structure, where you can easily iterate over them.

a0=[]
a1=[]
a2=[]
a3=[]
a4=[]

list_of_lists = [a0, a1, a2, a3, a4]

for k in range(len(mlac)):     # mlac.shape (17280, 5)
    for I in range(len(mlac[0])):
        list_of_lists[I].append(mlac[k][I])

The arrays are being passed by reference, so your original arrays will have their contents modified as you want.

Answered By: TheSoundDefense

Easy fix by Sembei:

A = [[],[],[],[],[]]
for k in range(len(mlac)):
    for i in range(len(mlac[0])):
        A[i].append(mlac[k][i])
Answered By: Lyu

Would using the eval() function be applicable to your use case?

Here is a simple code snippet demonstrating how it can be used:

a0=[]
a1=[]
a2=[]
a3=[]
a4=[]
a5=[]

mlac = [[y for y in range(5)] for x in range(5)] # Mock version of your mlac multidimentional array

for k in range(len(mlac)):     
    for I in range(len(mlac[0])):
        eval(f"a{I}.append(mlac[k][I])")

print(a0)
print(a1)
print(a2)
print(a3)
print(a4)

'''
Output:
[0, 0, 0, 0, 0]
[1, 1, 1, 1, 1]
[2, 2, 2, 2, 2]
[3, 3, 3, 3, 3]
[4, 4, 4, 4, 4]
'''

More examples on how to use the eval() function can be found here: Python eval(): Evaluate Expressions Dynamically

Answered By: flyingfishcattle