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))