【发布时间】:2017-10-05 09:02:11
【问题描述】:
我需要探索列表的每个排列。假设我有这个初始变量:
samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
一个示例输出是:
output = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 2, 4, 5, 6, 7, 8, 9], [1, 3, 4, 2, 5, 6, 7, 8, 9], [1, 3, 5, 3, 2, 6, 7, 8, 9]] .... and so on.
这就是我所做的:
import itertools
samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
list(combinations_with_replacement(samplelist, 9))
由于列表的长度为 9,因此 9 的阶乘为 362,880。我正在尝试获取列表中元素的所有这些组合
但我的输出不是我想要达到的。
【问题讨论】:
-
你
import itertools但从不使用它,相反你似乎是从文档中复制大致等效的 Python 代码,为什么不使用该模块? -
我认为我需要导入itertools,因为我在这里找到了函数源代码:docs.python.org/2/library/itertools.html
-
使用模块!喜欢
for comb in itertools.combinations(samplelist, 9): print(comb) -
您也可以使用较少项目(如 3 或 4)的输入。这样您就可以确定它是否按预期工作。
标签: python-3.x list itertools