colinong21
colinong21

Reputation: 3

Using a loop to generate new arrays from elements of pre-existing arrays [Python]

trying to achieve the following in a "for loop"
I have several arrays

a1=[a,b,c,d,e]
a2=[f,g,h,i,j]
a3=[k,l,m,n,o]

Using the loop, I hope to achieve new arrays

b1=[a,f,k]
b2=[b,g,l]....
b5=[e,j,o]

This is what I have :

totala=a1,a2,a3

for x in range (0,len(a1)):
    print([item[x] for item in totala])

this allows me to output what I want:[a,f,k] [b,g,l]...
However, i'm not entirely clear how to create the new arrays.

Any help would be useful!
Cheers

Upvotes: 0

Views: 200

Answers (3)

fameman
fameman

Reputation: 3869

If I understand you right, you want to create variables from the printed arrays. It's possible but I think, it's not the proper way to do that since your script would be very static (maybe you want to use a sixth character in the arrays. Then you would have to change your whole processings of the resulting b - variables). So I suggest you using a dictionary instead:

b_dict = {}
for x in range (0,len(a1)):
    print([item[x] for item in totala])
    b_dict[x+1] = [item[x] for item in totala] # i.e. 1: [a,f,k]

Afterwards you could process all your b's in a loop:

for key in b_dict:
    pass #process your b keys and b_dict[key] - values

If you really want to use b - variables you could do something like this:

for x in range (0,len(a1)):
    print([item[x] for item in totala])
    globals()["b" + str(x+1)] = [item[x] for item in totala]

Upvotes: 0

Giuseppe Angora
Giuseppe Angora

Reputation: 853

There are several different methods, one way:

result=[]
for a1_i, a2_i, a3_i in zip(a1,a2,a3):
    result.append([a1_i, a2_i, a3_i])

in this way you get a list where each element is the triplet you were looking for.

Another way is convert the lists in a numpy array:

import numpy as np
a1=np.array(a1)
a2=np.array(a2)
a3=np.array(a3)
a=np.array([a1,a2,a3])

Now if you read a by rows yuo get the original a1,a2,a3; instead if you read a by columns you get your triplet, try printing:

print(a[:, 0])
print(a.T) 

Upvotes: 0

Rahul K P
Rahul K P

Reputation: 16081

You can use zip.

map(list,zip(a1,a2,a3))

Execution

In [6]: for item in map(list,zip(a1,a2,a3)):
   ...:     print item
   ...:     
['a', 'f', 'k']
['b', 'g', 'l']
['c', 'h', 'm']
['d', 'i', 'n']
['e', 'j', 'o']

Upvotes: 1

Related Questions