如何将python列表的所有子集合并到n个容器中 - python

我有一个清单:

a = range(2)

并且我试图以所有可能的方式将列表的内容装到n(= 3)个装箱中,给出(顺序不重要):

[[[],[0],[1]],
[[],[1],[0]],
[[],[0,1],[]],
[[],[],[0,1]],
[[0],[1],[]],
[[0],[],[1]],
[[1],[0],[]],
[[1],[],[0]],
[[0,1],[],[]]]

到目前为止,我一直在使用sympy.utilities.iterables库,首先获取所有可能的子集,并过滤variations方法的输出以获得所需的结果:

def binner(a,n=3):
    import numpy as np
    import sympy.utilities.iterables as itt
    import itertools as it
    b = list(itt.subsets(a))    #get all subsets
    b.append(())                #append empty tuple to allow two empty bins
    c=list(itt.variations(b,n)) 
    d=[]
    for x in c:
        if np.sum(np.bincount(list(it.chain.from_iterable(x))))==len(a):
            d.append(x)     # add only combinations with no repeats and with all included
    return list(set(d))             # remove duplicates

我感觉有更好的方法可以做到这一点。有人可以帮忙吗?

注意,我不受sympy库的束缚,并且对任何基于python / numpy的替代方案都持开放态度。

python大神给出的解决方案

假设我了解您的目标(不确定在重复元素的情况下会发生什么,即是否想将它们区别对待),可以使用itertools.product:

import itertools

def everywhere(seq, width):
    for locs in itertools.product(range(width), repeat=len(seq)):
        output = [[] for _ in range(width)]
        for elem, loc in zip(seq, locs):
            output[loc].append(elem)
        yield output

这使

>>> for x in everywhere(list(range(2)), 3):
...     print(x)
...     
[[0, 1], [], []]
[[0], [1], []]
[[0], [], [1]]
[[1], [0], []]
[[], [0, 1], []]
[[], [0], [1]]
[[1], [], [0]]
[[], [1], [0]]
[[], [], [0, 1]]