2017-04-24 126 views
0

我想在python中创建一个函数,作为输入带有未指定数量字符串的列表,这些字符串的长度也不是标准或彼此相同。输入会是这样:找到Python的所有不同组合

list = ['1234', '4', '97', ... , '542'] 

这个列表的第一个元素代表了所有可能的数字,可以是数字,第二个元素可能数量的第一位,可能是第二个数字等等。作为输出,我想要列出所有可能以这种方式生成的数字。这里是一个例子:

input = ['12', '45', '865'] 
output = ['148', '146', '145', '158', '156', '155', 
'248', '246', '245', '258', '256', '255'] 

有没有一个算法呢?我对python并不是全新的,但这个问题让我不知所措。谢谢你的帮助。

回答

4
from itertools import product 

input = ['12', '45', '865'] 

[''.join(prod) for prod in product(*input)] 

# ['148', '146', '145', '158', '156', '155', '248', '246', 
# '245', '258', '256', '255'] 

itertools.product接受一个数字iterables作为参数,并产生它们的笛卡尔乘积。
由于您的迭代器(您的字符串)在列表中,我们使用*输入语法来解开列表元素以分隔位置参数。

1

测试与Python 2.7

Input = ['12', '45', '865'] 
out = [[]] 

# algo 
for liste in Input: 
    out = [x + [y] for x in out for y in liste] 
    #print out # un comment to see how algo works 

index = 0 
while index < len(out): 
    out[index] = ''.join(out[index]) 
    index += 1 

print out 

# prodcues: 
# ['148', '146', '145', '158', '156', '155', 
# '248', '246', '245', '258', '256', '255'] 
# The while loop can be reduced to: 
# print [''.join(liste) for liste in out]