我见过类似的但不一样的: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
哦最大排列长度(&#34; r&#34;在python.org itertools中)等于len(列表),我不想包括&#39;双重&#39;例如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个字符..白色。
答案 0 :(得分:6)
即使你&#34;肯定想要排列&#34;,听起来你真的不想要,你实际上想要你的序列的笛卡尔积与自己从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