创建可能案例的简单方法

时间:2010-03-29 05:24:05

标签: python methods module case

我有

等数据列表
a = [1,2,3,4]
b = ["a","b","c","d","e"]
c = ["001","002","003"]

我想创建一个新的另一个列表,混合了所有可能的a,b,c这样的情况

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

是否有任何模块或方法可以生成d而无需多次写入循环?

4 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分:1)

如果您将a转换为str的列表,这样做会更简单一些。 并且不必要地在b和c

的每个元素上调用str()
>>> 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']

这是时间比较

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

答案 2 :(得分:1)

这个怎么样?使用map

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

答案 3 :(得分:1)

map(''.join, itertools.product(map(str, a), b, c))