Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回列表的子组合_Python_Python 3.x - Fatal编程技术网

Python 返回列表的子组合

Python 返回列表的子组合,python,python-3.x,Python,Python 3.x,我有一个函数,它返回列表中的所有组合: def sub_combinations(segment): if len(segment) == 1: yield (segment,) else: for x, j in enumerate(sub_combinations(segment[1:])): yield ((segment[0],),)+j for k in range(len(j)): yield (((segment[0

我有一个函数,它返回列表中的所有组合:

def sub_combinations(segment):
  if len(segment) == 1:
    yield (segment,)
  else:
    for x, j in enumerate(sub_combinations(segment[1:])):
      yield ((segment[0],),)+j
      for k in range(len(j)):
         yield (((segment[0],)+j[k]),) + (j[:k]) +(j[k+1:])
但如何使其仅返回子组合:

((1,), (2,), (3,), (4,))
((1, 2), (3,), (4,))
((1, 3), (2,), (4,))
((1, 4), (2,), (3,))
((1,), (2, 3), (4,))
((1, 2, 3), (4,))
((1, 4), (2, 3))
((1,), (2, 4), (3,))
((1, 2, 4), (3,))
((1, 3), (2, 4))
((1,), (2,), (3, 4))
((1, 2), (3, 4))
((1, 3, 4), (2,))
((1,), (2, 3, 4))
而不是:

((1,), (2,), (3,), (4,))
((1, 2), (3,), (4,))
((1, 3), (2,), (4,))
((1, 4), (2,), (3,))
((1,), (2, 3), (4,))
((1, 2, 3), (4,))
((1, 4), (2, 3))
((1,), (2, 4), (3,))
((1, 2, 4), (3,))
((1, 3), (2, 4))
((1,), (2,), (3, 4))
((1, 2), (3, 4))
((1, 3, 4), (2,))
((1,), (2, 3, 4))
((1, 2, 3, 4),)  # remove this
使用以下命令调用时:

sub_combinations((1,2,3,4))
这是我的尝试,但没有成功:

def sub_combinations(segment, d=0):
  if len(segment) == 1:
    yield (segment,)
  else:
    for x, j in enumerate(sub_combinations(segment[1:]), d+1):
      yield ((segment[0],),)+j
      for k in range(len(j)):
         r = (((segment[0],)+j[k]),) + (j[:k]) +(j[k+1:])
         if d == 0 and r == (segment,): continue
         yield r

我认为你应该分成两个函数,每个函数都有自己的功能。第一种方法只是在实现时创建组合,第二种方法只是包装它,并过滤不需要的片段

比如:

from itertools import filterfalse

def get_combinations(segment):
    pass # your implementation


def get_sub_combinations(segment, filter_func=lambda x: x == segment):
    yield from filterfalse(filter_func, get_combinations(segment))