Aymen Derradji
Aymen Derradji

Reputation: 318

python combine array item by item

if i have three arrays the first one is A,B,C,D and the second one is E,F,G,H and the last one is I,J,K,L i want to use this three array and make an output like this :

AEI
BFJ
CGK
DHL

i try this code

import re
array1 = 'A','B','C','D'
array2 = 'E','F','G','H'
array3 = 'I','J','K','L'
arys = [array1,array2,array3]

for a,b,c,d in arys:
    print a+b+c+d

it didnt work

how to make this work

Upvotes: 0

Views: 231

Answers (3)

Max Kanwal
Max Kanwal

Reputation: 61

Here is one simple way (you definitely want to use zip() here):

array1 = 'A','B','C','D'
array2 = 'E','F','G','H'
array3 = 'I','J','K','L'

for triplet in zip(array1, array2, array3):
    print ''.join(triplet)

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

You can also do it with map in python2:

array1 = 'A','B','C','D'
array2 = 'E','F','G','H'
array3 = 'I','J','K','L'
print("\n".join(map("".join, map(None, array1, array2, array3))))
AEI
BFJ
CGK
DHL

Upvotes: 1

Bahrom
Bahrom

Reputation: 4862

Try this:

array1 = 'A','B','C','D'
array2 = 'E','F','G','H'
array3 = 'I','J','K','L'
for elems in zip(array1, array2, array3):
    print ''.join(elems)

It prints

AEI
BFJ
CGK
DHL

Edit: you could also just zip the 3 strings together instead of creating tuples and get the same output:

for elems in zip("ABCD", "EFGH", "IJKL"):
    print(''.join(elems))

Upvotes: 4

Related Questions