本文介绍了使用itertools获取设置的python的所有分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取集合的所有分区?
How to get all partitions of a set?
例如,我有一个数组 [1、2、3]
.我需要获取 [[1],[2],[3]],[[1],[2、3]],[[2],[1,3]],[[3],[1、2]],[[1、2、3]]
.
For example, I have array [1, 2, 3]
. I need to get [[1], [2], [3]], [[1], [2, 3]], [[2], [1,3]], [[3], [1, 2]], [[1, 2, 3]]
.
现在,我编写了这段代码:
Now, I wrote this code:
def neclusters(S, K):
for splits in itertools.combinations(range(len(S)), K):
yield np.split(S, 1 + np.array(splits))
但是该代码不会返回 [[2],[1,3]]
.
我可以获取原始集合的所有排列并在其上运行此代码.但这可以变得更容易吗?
I could take all permutations of the original set and run this code on them. But can this be made easier?
推荐答案
我写这个很有趣:
def partition(a_list):
yield [[x] for x in a_list]
for i in range(1, len(a_list) + 1):
_l = a_list[:]
yield [_l.pop(i-1), _l]
yield a_list
my_list = [1, 2, 3]
print list(partition(my_list))
#or
for p in partition(my_list):
print p
这篇关于使用itertools获取设置的python的所有分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!