问题描述
我看到了相似但不相同的内容:这里.我绝对希望所有列表元素的排列而不是组合.我的是不同的,因为itertools排列的a,b,c返回abc而不是aba(soooo close).如何获得像aba这样的结果?
I have seen similar but not the same: here.I definitely want the permutations, not combinations, of all list elements. Mine is different because itertools permutation of a,b,c returns abc but not aba (soooo close).How can I get results like aba returned as well?
('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该列表可以是任意长度.
Oh max length of permutations ("r" in the python.org itertools) is equal to len(list), and I don't want to include 'doubles' such as aab or abb ...or abba :P The list could be any length.
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循环
I combined the above into a for loop
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个结果.
For reference, when I did this on paper I got 21 results.
将字符串列表转换为数字列表也有任何好处.我的想法是,对于排列工具而言,数字将更易于使用.字符串可能是10到50个字符..ish.
Also is there any merit in converting the list of strings into a list of numbers. My thought was that numbers would be easier to work with for the permutations tool. Strings might be 10 to 50 chars..ish.
推荐答案
即使您绝对想要排列",听起来您也不是想要的,您实际上想要序列的笛卡尔积与1到len(sequence)次,相邻元素相等的结果被滤除.
Even though you "definitely want the permutations", it sounds like you don't really want that, you actually want the Cartesian product of your sequence with itself from 1 to len(sequence) times, with results with neighbouring equal elements filtered out.
类似的东西:
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
这篇关于具有重复但不加倍的列表的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!