2017-10-30 2 views
0

私は同様ですが同じではありません:hereを見ました。 の順列が、すべてのリスト要素の組み合わせではなく、間違いなく必要です。私の違いは、a、b、cのitertools順列はabcを返しますが、aba(soooo close)は返しません。 abaのような結果も返されますか?順列の繰り返しのリストのすべての順列は二重ではありません。

('a',)  <-excellent 
('b',)  <-excellent 
('c',)  <-excellent 
('a', 'b') <-excellent 
('a', 'c') <-excellent 
('b', 'a') <-excellent 
('b', 'c') <-excellent 
('c', 'a') <-excellent 
('c', 'b') <-excellent 
('a', 'b', 'c') <-- I need a,b,a 
('a', 'c', 'b') <-- I need a,c,a 
('b', 'a', 'c') <-- I need b,a,b... you get the idea 

ああ最大長(python.orgのitertoolsの「R」)は、LEN(リスト)に等しく、私はそのようなAABまたはABBなど「ダブルス」を含めたくありません...またはabba:Pリストは任意の長さにすることができます。

import itertools 
from itertools import product 
my_list = ["a","b","c"] 
#print list(itertools.permutations(my_list, 1)) 
#print list(itertools.permutations(my_list, 2)) 
#print list(itertools.permutations(my_list, 3)) <-- this *ALMOST* works 

私は参考のためforループ

def all_combinations(varsxx): 
    repeat = 1 
    all_combinations_result = [] 
    for item in varsxx: 
     if repeat <= len(varsxx): 
      all_combinations_result.append(list(itertools.permutations(varsxx, repeat))) 
     repeat += 1 
    return all_combinations_result 

に上記を組み合わせた私は紙の上にこれをしたときに、私は21件の結果を得ました。

また、文字列のリストを数字のリストに変換するメリットがあります。私の思想は、パーミュテーションツールでは数字が使いやすくなるということでした。文字列は10から50文字です。

+2

は、あなたが正確に、より正確にしたいかを説明する必要があります。 –

答えて

6

あなたが「間違いなく並べ替えをしたい」とは言っても、本当にそれが欲しいとは思わないが、実際にはシーケンス自体のカーテシアン積が1からlen(シーケンス)要素が除外されます。以下のような

何か:

In [16]: from itertools import product 

In [17]: def has_doubles(x): return any(i==j for i,j in zip(x, x[1:])) 

In [18]: seq = ["a","b","c"] 

In [19]: [x for n in range(len(seq)) for x in product(seq, repeat=n+1) 
      if not has_doubles(x)] 
Out[19]: 
[('a',), 
('b',), 
('c',), 
('a', 'b'), 
('a', 'c'), 
('b', 'a'), 
('b', 'c'), 
('c', 'a'), 
('c', 'b'), 
('a', 'b', 'a'), 
('a', 'b', 'c'), 
('a', 'c', 'a'), 
('a', 'c', 'b'), 
('b', 'a', 'b'), 
('b', 'a', 'c'), 
('b', 'c', 'a'), 
('b', 'c', 'b'), 
('c', 'a', 'b'), 
('c', 'a', 'c'), 
('c', 'b', 'a'), 
('c', 'b', 'c')] 

In [20]: len(_) 
Out[20]: 21 
+0

それは素晴らしいです、あなたは1つにそれを釘付け! :) コードは1回目に働き、ダブルスは削除され、 "製品"はすべてそこにあり、数は正しいですし、大きなリストでも機能します:) Nailed * everything * :)多くの感謝! – DaftVader

+0

もう一度お手伝いしていただきありがとうございます。もう一度お願いしてもらえますか?代わりに結果をYIELDする必要がありますが、これを変更しようとする私の試みは不得手です。 結果の上に「ステップ」する必要があります。 IEは結果( 'a'、)を取得し、それを処理します。その後、( 'b'、) – DaftVader

関連する問題