2017-12-05 3 views
0

どのように私はPythonで長さnのリストのすべての可能な組み合わせを得ることができますが、私は文字列のコードを書いたが、上記のコードpythonで長さnのリストのすべての可能な組み合わせitertoolsなし

def combo(w, l): 
    lst = [] 
    for i in range(len(w)): 
     if l == 1: 
      lst.append(w[i]) 
     for c in combo(w[i+1:], l-1): 
      lst.append(w[i] + c) 
    return lst 

comb=map(list,combo('12345',3)) 

文字列の組み合わせを得ることです、それは正しい出力を与える:

['12', '13', '14', '15', '23', '24', '25', '34', '35', '45'] 

答えて

0

あなたはまた、単にitertools.combinationsを使用することができます。

>>> import itertools 

>>> print(["".join(x) for x in itertools.combinations('12345', 2)]) 
['12', '13', '14', '15', '23', '24', '25', '34', '35', '45'] 

>>> print([list(x) for x in itertools.combinations(['1', '2', '3', '4', '5'], 2)]) 
[['1', '2'], ['1', '3'], ['1', '4'], ['1', '5'], ['2', '3'], ['2', '4'], ['2', '5'], ['3', '4'], ['3', '5'], ['4', '5']] 

>>> print(["".join(x) for x in itertools.combinations(['1', '2', '3', '4', '5'], 2)]) 
['12', '13', '14', '15', '23', '24', '25', '34', '35', '45'] 
+0

itertools.combinations(['1'、 '2'、 '3'、 '4'、 '')のリスト要素 'print '[" "。join(x) ''、 '13'、 '14'、 '15'、 '23'、 '24'、 '25'、 '34'、 ' 35 '、' 45 ']' – Manjunath

+0

@Manjunathが追加されました。 – RoadRunner

+0

これを追加していただきありがとうございます。 – Manjunath

0

あなたはこのを探しています:

import itertools 


def combinations(list_1): 
    split_list=[item for item in list_1[0]] 
    return [''.join(sub_item) for sub_item in itertools.combinations(split_list,r=2)] 

print(combinations(['12345'])) 

出力:もちろん

['12', '13', '14', '15', '23', '24', '25', '34', '35', '45'] 
0

、そこutilsのはitertoolsであるが、次のように次の2本のラインを調整することによって、あなたの関数を修正することができます:

# note the '[]' around w[i] in those lines 
lst.append([w[i]]) 
# ... 
lst.append([w[i]] + c) 
# ... 

文字列は、その要素は(意味でユニークな配列でありますchars so speak)は文字列そのものであり、+によって連結することができます。他のほとんどのシーケンス/反復可能な型では、シーケンスとその要素を明確に区別しなければなりません。この場合、要素ではなく、リストを連結したいと考えています。

+0

ありがとうございました –

関連する問題