在Python中,如何创建可变长度的组合或排列? [英] In Python how do I create variable length combinations or permutations?
问题描述
假设我有一个名为arr = [1,2,3,4]的数组
Lets say I have an array called arr = [1,2,3,4]
如何生成带有至少2个参数的所有可能组合,最终看起来像这样
How can I generate all the possible combinations with minimum 2 arguments that end up looking like
[1,2]
[1,3]
[1,4]
[1,2,3]
[1,2,4]
[1,2,3, 4]
[2,3]
[2,4]
等等,依此类推?我没有尝试的方法.我似乎无法使用itertools.combinations或置换,因为我需要知道参数的大小,而我似乎无法使用itertools.products,因为它将从看起来像 [[1],[2],[3],[4],[5]]
.特别感谢您的班轮和理解.
and so on and so forth? Nothing Im trying works. I cant seem to use itertools.combinations or permutations because I need to know the argument size and I cant seem to use itertools.products because that will take minimum one argument from each of a list of lists that looks like this [[1],[2],[3],[4],[5]]
. Extra thanks for one liners and comprehensions.
如果我想将它们全部加在一起,那么就需要太多帮助了吗?;-)
If I wanted to add them all together would that be too much to ask in terms of help? ;-)
推荐答案
怎么样:
(x for l in range(2, len(arr)) for x in itertools.combinations(arr, l))
或
[x for l in range(2, len(arr)) for x in itertools.combinations(arr, l)]
如果您需要列表.
这等效于以下嵌套循环
res = []
for l in range(2, len(arr)):
for x in itertools.combinations(arr, l):
res.append(x)
return res
这篇关于在Python中,如何创建可变长度的组合或排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!