大型迭代器的笛卡尔积(itertools)

Hoo*_*ked 14 python memory cartesian-product python-itertools

从前一个问题我学到了一些有趣的东西.如果Python itertools.product是由一系列迭代器提供的,那么这些迭代器将在笛卡尔积开始之前转换为元组.相关 问题查看源代码,itertools.product得出结论:虽然没有中间结果存储在内存中,但是在产品迭代开始之前创建了原始迭代器的元组版本.

问题:当(元组转换的)输入太大而无法保存在内存中时,有没有办法为笛卡尔积创建迭代器?琐碎的例子:

import itertools
A = itertools.permutations(xrange(100))
itertools.product(A)
Run Code Online (Sandbox Code Playgroud)

一个更实际的用例将采用一系列(*iterables[, repeat])类似于函数的原始实现 - 上面只是一个例子.它看起来不像你可以使用当前的实现itertools.product,所以我欢迎在纯python中提交(虽然你不能击败C后端itertools!).

eca*_*mur 5

这是一个调用callables并迭代iterables的实现,它们被认为是可重启的:

def product(*iterables, **kwargs):
    if len(iterables) == 0:
        yield ()
    else:
        iterables = iterables * kwargs.get('repeat', 1)
        it = iterables[0]
        for item in it() if callable(it) else iter(it):
            for items in product(*iterables[1:]):
                yield (item, ) + items
Run Code Online (Sandbox Code Playgroud)

测试:

import itertools
g = product(lambda: itertools.permutations(xrange(100)),
            lambda: itertools.permutations(xrange(100)))
print next(g)
print sum(1 for _ in g)
Run Code Online (Sandbox Code Playgroud)