All possibilities to split a list into two lists

前端 未结 4 1866
遇见更好的自我
遇见更好的自我 2020-12-18 23:18

I have a list with some elements and want to iterate over all possible ways to divide this list into two lists. By that I mean all combinations, so the order doesn\'t matter

4条回答
  •  感动是毒
    2020-12-19 00:09

    Just extending @Ouroborus solution using filters and keeping the results together:

    import itertools as it
    
    # itertools recipe
    def partition(pred, iterable):
        t1, t2 = it.tee(iterable)
        return it.filterfalse(pred, t1), filter(pred, t2)
    
    >>> facs = ['one','two','three']
    >>> [[[x[1] for x in f] for f in partition(lambda x: x[0], zip(pattern, facs))]
    ...  for pattern in product([True, False], repeat=len(facs))]
    [[[], ['one', 'two', 'three']],
     [['three'], ['one', 'two']],
     [['two'], ['one', 'three']],
     [['two', 'three'], ['one']],
     [['one'], ['two', 'three']],
     [['one', 'three'], ['two']],
     [['one', 'two'], ['three']],
     [['one', 'two', 'three'], []]]
    

提交回复
热议问题