0

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

2
  • use zip() and store values in a dict rather than dynamically creating new variables Commented Jul 31, 2017 at 9:26
  • What do you mean? you are creating the new lists. Commented Jul 31, 2017 at 9:35

3 Answers 3

1

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']
Sign up to request clarification or add additional context in comments.

Comments

0

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]

2 Comments

Thanks! this is exactly what i'm looking for. Cheers on the heads up for dictionaries. Just started learning coding and have not really used dictionaries for problems before. thanks once again
I'm glad I could help you. Welcome to the world of coding ;-)
0

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) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.