使用itertools获取python集合的所有分区

atmip9wb  于 2023-06-28  发布在  Python
关注(0)|答案(3)|浏览(118)

如何获取集合的所有分区?
例如,我有一个数组[1, 2, 3]。我需要得到[[1], [2], [3]], [[1], [2, 3]], [[2], [1,3]], [[3], [1, 2]], [[1, 2, 3]]
现在,我写了这个代码:

def neclusters(S, K):
    for splits in itertools.combinations(range(len(S)), K):
       yield np.split(S, 1 + np.array(splits))

但该代码不返回[[2],[1,3]]
我可以把原始集合的所有排列,并在它们上面运行这个代码。但是,这可以变得更容易吗?

e1xvtsh3

e1xvtsh31#

我写这篇文章是为了好玩:

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
dfty9e19

dfty9e192#

a = [1, 2, 3]
b = list()
for l in range(len(a)+1): b.append([c for c in combinations(a, l)])

print(b)

检查这个

avwztpqn

avwztpqn3#

这个函数是more_itertools.powerset(),没有其他答案指向它,所以我把它留在这里。
https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.powerset

相关问题