首页 > 解决方案 > 列表列表中的组合

问题描述

拥有以下列表列表['boundari', 'special', ['forest', 'arb'], 'abod'],我想获得以下组合:

[['boundari', 'special', 'forest', 'abod'], ['boundari', 'special', 'arb', 'abod']]

abod删除最后一项(我需要保留)时应用下一个产品的最近解决方案:

print([list(p) for p in product([toks[:2]], *toks[2:])])

[[['boundari', 'special'], 'forest'], [['boundari', 'special'], 'arb']]

但是,我没有得到正确的组合:

 [['boundari', 'special', 'forest', 'abod'], ['boundari', 'special', 'arb', 'abod']]

标签: pythonlist

解决方案


你可以这样做:

arr = ['boundari', 'special', ['forest', 'arb'], 'abod']


def get_combinations(arr):
    n = len(arr)

    def _get_combinations(so_far, idx):
        if idx >= n:
            yield so_far[:]
            return

        if isinstance(arr[idx], list):
            for val in arr[idx]:
                so_far.append(val)
                yield from _get_combinations(so_far, idx + 1)
                so_far.pop()
        else:
            so_far.append(arr[idx])
            yield from _get_combinations(so_far, idx + 1)
            so_far.pop()

    yield from _get_combinations([], 0)


expected_ans = [
    ['boundari', 'special', 'forest', 'abod'], 
    ['boundari', 'special', 'arb', 'abod'],
]
assert list(get_combinations(arr)) == expected_ans

推荐阅读