[英]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.