2017-04-24 117 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]