[英]How can I take multiple combinations of the different lengths from the same list in python?
Suppose I have the tuple (3, 2, 1, 4). 假设我有元组(3,2,1,4,4)。 I would like to find every possible combination that involves taking 3 elements from range(5), 2 elements from range(5), 1 elements from range(5), and then 4 elements from range(5).
我想找到每种可能的组合,其中涉及从range(5)取3个元素,从range(5)取2个元素,从range(5)取1个元素,然后从range(5)取4个元素。 The order between each individual combination matters, so I cannot just take combinations of length 9 from range(5) or something like that.
每个单独的组合之间的顺序都很重要,因此我不能只接受range(5)或类似的长度9的组合。
In case what I wrote above wasn't clear, a sample combination might be 如果我上面写的不清楚,可以使用示例组合
[0, 1, 4, 2, 3, 2, 0, 1, 2, 3].
I introduced the spacing in the list above just to make it clear that the ordering between them matters. 我在上面的列表中介绍了间距,只是为了清楚地说明它们之间的顺序很重要。
I imagine that this should be simple to implement with itertools, but I just don't know how. 我认为使用itertools实现起来应该很简单,但是我只是不知道怎么做。
Assuming you are looking for combinations rather than permutations , the following should do what you want. 假设您正在寻找组合而不是排列 ,那么以下应该做您想要的。
from itertools import chain, combinations, product
lengths = (3, 2, 1, 4)
for L in product(*(combinations(range(5), length) for length in lengths)):
print(list(chain.from_iterable(L)))
if the order is important for you this give you what you want : 如果订单对您很重要,这会给您您想要的东西:
>>> l1=list(combinations(range(5), 1))
>>> l2=list(combinations(range(5), 2))
>>> l3=list(combinations(range(5), 3))
>>> l4=list(combinations(range(5), 4))
>>> tl=[l3,l2,l1,l4]
>>> list(product(*tl))
[((0, 1, 2), (0, 1), (0,), (0, 1, 2, 3)), ((0, 1, 2), (0, 1), (0,), (0, 1, 2, 4)), ((0, 1, 2), (0, 1), (0,), (0, 1, 3, 4)), ((0, 1, 2), (0, 1), (0,), (0, 2, 3, 4)), ((0, 1, 2), (0, 1), (0,), (1, 2, 3, 4)), ((0, 1, 2), (0, 1), (1,), (0, 1, 2, 3)), ((0, 1, 2), (0, 1), (1,), (0, 1, 2, 4)), ((0, 1, 2), (0, 1), (1,), (0, 1, 3, 4)), ((0, 1, 2), (0, 1), (1,), (0, 2, 3, 4)), ((0, 1, 2), (0, 1), (1,), (1, 2, 3, 4)), ((0, 1, 2), (0, 1), (2,), (0, 1, 2, 3)), ((0, 1, 2), (0, 1), (2,), (0, 1, 2, 4)), ((0, 1, 2), (0, 1), (2,), (0, 1, 3, 4)), ((0, 1, 2), (0, 1), (2,), (0, 2, 3, 4)), ((0, 1, 2), (0, 1), (2,), (1, 2, 3, 4)), ((0, 1, 2), (0, 1), (3,), (0, 1, 2, 3)), ((0, 1, 2), (0, 1), (3,), (0, 1, 2, 4)), ((0, 1, 2), (0, 1), (3,), (0, 1, 3, 4)), ((0, 1, 2), (0, 1), (3,), (0, 2, 3, 4)), ((0, 1, 2), (0, 1), (3,), (1, 2, 3, 4)), ((0, 1, 2), (0, 1), (4,), (0, 1, 2, 3)), ((0, 1, 2), (0, 1), (4,), (0, 1, 2, 4)), ((0, 1, 2), (0, 1), (4,), (0, 1, 3, 4)), ((0, 1, 2), (0, 1), (4,), (0, 2, 3, 4)), ((0, 1, 2), (0, 1), (4,), (1, 2, 3, 4)), ((0, 1, 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.