如何将python列表的所有子集分成n个bin

时间:2015-05-26 10:14:26

标签: python numpy combinations sympy itertools

我有一个清单:

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的替代方案开放。

3 个答案:

答案 0 :(得分:4)

假设我理解你的目标(不确定在重复元素的情况下你可能想要发生什么,即你是否想要将它们视为不同),你可以使用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]]

答案 1 :(得分:1)

from itertools import permutations

a = range(2)


# get all the possible combinations

indexes = ','.join([str(i) for i in range(len(a))])+","
comb = []
perms = [''.join(p) for p in permutations(indexes)]
for x in perms:
    candidate = [[int(i) for i in  list(s)] if len(s) !=0 else [] for s in x.split(',') ]
    if candidate not in comb and [row[::-1] for row in candidate] not in comb:
        comb.append(candidate)

for item in comb:
    print item
>>
 [[0], [1], []]
 [[0], [], [1]]
 [[0, 1], [], []]
 [[], [0, 1], []]
 [[], [0], [1]]
 [[], [1], [0]]
 [[], [], [0, 1]]
 [[1], [0], []]
 [[1], [], [0]]

答案 2 :(得分:0)

如何编写递归函数来执行此操作?

基本理念是

    如果bins == 1,
  1. subset(bins, l)等于[l],因为你有 一个箱子放置值
  2. subset(bins, l) = l[i] + subset(bins-1, lp)其中lp = l没有 升[I]

    <强> +

    [l] + subset(bins-1, []) - &gt;将所有装入一个箱子中 的 +

    [] + subset(bins, l) - &gt;没有进入垃圾箱

  3. 因此subset(3, [0, 1]) = [[0] + subset(2, [1])[1] + subset(2, [0])[0, 1] , subset(2, [])[] + subset(2, [])]

    代码就像

    def subset(bins, l):
        if bins == 1:
            if l == []:
                return [[]]
            return [[l]]
        all_possible = []
        for i in range(len(l)): # choosing one element 
            a = l[:]
            x = l[i]
            a.pop(i)
            if len(a) > 0:
                y = subset(bins-1, a) # recurse for that list minus chosen one
                for j in y:
                    all_possible.append([[x]] + j)
        y = subset(bins-1, l) # dont take out any element
        for j in y:
            all_possible.append([[]] + j)
        y = [[]] * (bins-1) # take out all elements
        all_possible.append([l] + y)
        return all_possible
    

    输出 -

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