![](/img/trans.png)
[英]Splitting a word into all possible 'subwords' - All possible combinations
[英]Split an array in all possible combinations (not regular splitting)
請在投票前仔細閱讀此問題。 我在這里的其他問題中找不到我的問題。
假設我有一個數組,
>>> import numpy as np
>>> array = np.linspace(1,4,4, dtype=np.int)
>>> array
array([1, 2, 3, 4])
我想要一個 function 將這個數組分割成所有可能的部分,這樣,
沒有拆分:
([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)
將給出,
[array([0, 1]), array([2, 3])]
正如你所看到的,這不是我需要的。 如何滿足我的需求?
您可以使用itertools.combinations
生成索引,以在拆分次數內循環內拆分:
>>> 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])]]
對numpy不熟悉,但是您可以使用除法和征服(無論是否在此位置分割)在純python中完成:
def split(a):
if not a:
return [[]]
elif len(a) == 1:
return [[a]]
else:
result = []
for i in range(1, len(a) + 1):
result += [(a[:i], *sub_split) for sub_split in split(a[i:])]
return result
split([1,2,3])
# output => [([1], [2], [3]), ([1], [2, 3]), ([1, 2], [3]), ([1, 2, 3],)]
為任務尋找線索,我來到了這里。 這是我的提議。
from more_itertools import partitions
def partitions_as_string(string):
return [part for part in partitions(string) if len(part) > 1]
print(partitions_as_string([1,2,3,4]))
結果:
[[[1], [2, 3, 4]], [[1, 2], [3, 4]], [[1, 2, 3], [4]], [[1], [2], [3, 4]], [[1], [2, 3], [4]], [[1, 2], [3], [4]], [[1], [2], [3], [4]]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.