[英]ALL permutations of a list with repetition but not doubles
我見過類似但不同的東西: 這里 。 我絕對想要所有列表元素的排列而不是組合。 我的是不同的,因為itertools排列的a,b,c返回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(list),我不想包含“雙精度”,例如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個字符。
即使您“絕對想要排列”,這聽起來似乎也不是您想要的,但實際上您想要的是序列本身的笛卡爾乘積,其范圍是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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.