2010-03-29 31 views
3

我如简单的方法来创造可能的情况下

a = [1,2,3,4] 
b = ["a","b","c","d","e"] 
c = ["001","002","003"] 

数据的列表和我想创造新的另一个列表是由A,B的所有可能的情况下混合,C喜欢这个

d = ["1a001","1a002","1a003",...,"4e003"] 

是否有任何模块或方法来生成d没有写多为循环?

回答

13
[''.join(str(y) for y in x) for x in itertools.product(a, b, c)] 
1

这是一个稍微简单做,如果你转换a是的str列表了。 并节省不必要的呼叫b各自元件和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'] 

上。这里str()是一个定时比较

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 
1

怎么样?使用map

print [''.join(map(str,y)) for y in itertools.product(a,b,c)] 
+0

返回'[ '1a001', '2b002', '3c003']' – 2010-03-29 09:20:45

1
map(''.join, itertools.product(map(str, a), b, c)) 
相关问题