Cartesian product of large iterators (itertools)

前端 未结 4 2194
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 15:56

From a previous question I learned something interesting. If Python\'s itertools.product is fed a series of iterators, these iterators will be converted into tu

4条回答
  •  醉话见心
    2020-12-17 16:41

    Here's an implementation which calls callables and iterates iterables, which are assumed restartable:

    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
    

    Testing:

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

提交回复
热议问题