Fiona
Fiona

Reputation: 273

How to implement this list in a simple way

With python2.7, I want to generate a new list and the input/output is as below. Want to make a simple way to do it...

input:

l1=['1','2'] 
l2=['a','b','c','d']
l3=['x','y','z']

#expect output:
['1ax','1bx','1cx','2dx','1ay','1by','1cy','2dy',.......]

Upvotes: 0

Views: 53

Answers (2)

oppressionslayer
oppressionslayer

Reputation: 7204

You can change the multipliers to go further but this get's you to an even number:

from functools import reduce
import operator
l1=['1','2'] 
l2=['a','b','c','d']
l3=['x','y','z']

newlist=[] 
for item in zip(l1*6,l2*3,l3*4): 
   newlist.append(reduce(operator.add, item)) 

newlist 
#['1ax', '2by', '1cz', '2dx', '1ay', '2bz', '1cx', '2dy', '1az', '2bx', '1cy', '2dz']

Upvotes: 0

Subhrajyoti Das
Subhrajyoti Das

Reputation: 2710

Use the below code:

l1=['1','2'] 
l2=['a','b','c','d']
l3=['x','y','z']

final_arr = list()
for i in l1:
    for j in l2:
        for k in l3:
            final_arr.append('{}{}{}'.format(i,j,k))

print(final_arr)
['1ax', '1ay', '1az', '1bx', '1by', '1bz', '1cx', '1cy', '1cz', '1dx', '1dy', '1dz', '2ax', '2ay', '2az', '2bx', '2by', 
'2bz', '2cx', '2cy', '2cz', '2dx', '2dy', '2dz']

Upvotes: 1

Related Questions