以所有可能的组合拆分数组(非常规拆分) [英] Split an array in all possible combinations (not regular splitting)
问题描述
在投反对票之前,请仔细阅读此问题.在这里的其他问题中找不到我的问题.
Please read this question carefully before down voting. I could not find my problem in other questions here.
假设我有一个数组,
>>> import numpy as np
>>> array = np.linspace(1,4,4, dtype=np.int)
>>> array
array([1, 2, 3, 4])
我想要一个函数,可以将该数组拆分为所有可能的部分,例如,
I want a function that will split this array in all possible parts, such that,
不拆分:
([1,2,3,4])
分为2
个部分:
([1], [2,3,4])
([1,2], [3,4])
([1,2,3] ,[4])
分为3
个部分:
([1], [2], [3,4])
([1,2]), [3], [4])
([1], [2,3], [4])
分为len(array)
个部分:
([1],[2],[3],[4])
我知道有np.split(array, r)
,但是不会给出所有可能的分割.例如np.split(array, 2)
会给出
I know there is np.split(array, r)
, but it will not give all possible splits. e.g. np.split(array, 2)
will give,
[array([0, 1]), array([2, 3])]
如您所见,这不是我所需要的.如何满足我的需求?
As you can see this is not what I need. How to achieve my need?
推荐答案
您可以使用
You could use itertools.combinations
to generate the indices where to split inside a loop over the number of splits:
>>> from itertools import combinations
>>> [np.split(array, idx)
... for n_splits in range(5)
... for idx in combinations(range(1, len(array)), n_splits)]
[[array([1, 2, 3, 4])],
[array([1]), array([2, 3, 4])],
[array([1, 2]), array([3, 4])],
[array([1, 2, 3]), array([4])],
[array([1]), array([2]), array([3, 4])],
[array([1]), array([2, 3]), array([4])],
[array([1, 2]), array([3]), array([4])],
[array([1]), array([2]), array([3]), array([4])]]
这篇关于以所有可能的组合拆分数组(非常规拆分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!