【发布时间】:2017-10-30 05:15:15
【问题描述】:
我见过类似但不一样的:here。 我绝对想要所有列表元素的排列,而不是组合。我的不同,因为 a,b,c 的 itertools 排列返回 abc 但不返回 aba(非常接近)。 我怎样才能得到像 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 个字符..ish。
【问题讨论】:
-
你需要更准确地描述你到底想要什么。
标签: python permutation itertools