生成包含列表列表

时间:2017-02-18 05:18:55

标签: python python-3.x

基本上我想要All combinations of a list of lists中提出的问题, 但只使用while或/和for循环。换句话说,不使用itertools也不使用递归。

我知道以前曾经问过许多类似的问题,但不幸的是我找不到想要的答案。我已经找到了一些使用循环和递归的解决方案,但是当我试图将它们转换为仅循环时,我发现它对我不起作用。我曾考虑将for循环放在while循环中,但它的工作方式与使用递归不同,因为整个for循环在另一个while循环开始之前完成。

我已经坚持了几个小时,非常感谢任何帮助/提示。我正在使用Python 3!

1 个答案:

答案 0 :(得分:0)

好吧,如果您要求仅使用for循环实现itertools.product,那么您将在documentation中找到相同的内容。

def product(*args, repeat=1):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)