问题
How to get all partitions of a set?
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))
But that code don't return [[2],[1,3]]
.
I could take all permutations of the original set and run this code on them. But can this be made easier?
回答1:
I wrote this one for fun:
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
回答2:
a = [1, 2, 3]
b = list()
for l in range(len(a)+1): b.append([c for c in combinations(a, l)])
print(b)
check this
来源:https://stackoverflow.com/questions/42704932/get-all-the-partitions-of-the-set-python-with-itertools