I have lists of data such as
a = [1,2,3,4]
b = ["a","b","c","d","e"]
c = ["001","002","003"]
And I want to create new another list that was mixed from all possible case of a,b,c like this
d = ["1a001","1a002","1a003",...,"4e003"]
Is there any module or method to generate d without write many for loop?
[''.join(str(y) for y in x) for x in itertools.product(a, b, c)]
This is a little simpler to do if you convert a
to be a list of str
too.
and saves needlessly calling str()
on each element of b and c
>>> from itertools import product
>>> a = [1,2,3,4]
>>> b = ["a","b","c","d","e"]
>>> c = ["001","002","003"]
>>> a = map(str,a) # so a=['1', '2', '3', '4']
>>> map(''.join, product(a, b, c))
['1a001', '1a002', '1a003', '1b001', '1b002', '1b003', '1c001', '1c002', '1c003', '1d001', '1d002', '1d003', '1e001', '1e002', '1e003', '2a001', '2a002', '2a003', '2b001', '2b002', '2b003', '2c001', '2c002', '2c003', '2d001', '2d002', '2d003', '2e001', '2e002', '2e003', '3a001', '3a002', '3a003', '3b001', '3b002', '3b003', '3c001', '3c002', '3c003', '3d001', '3d002', '3d003', '3e001', '3e002', '3e003', '4a001', '4a002', '4a003', '4b001', '4b002', '4b003', '4c001', '4c002', '4c003', '4d001', '4d002', '4d003', '4e001', '4e002', '4e003']
Here is a timing comparison
timeit astr=map(str,a);map(''.join, product(astr, b, c))
10000 loops, best of 3: 43 us per loop
timeit [''.join(str(y) for y in x) for x in product(a, b, c)]
1000 loops, best of 3: 399 us per loop
map(''.join, itertools.product(map(str, a), b, c))
How about this? Using map
print [''.join(map(str,y)) for y in itertools.product(a,b,c)]