Cartesian product of large iterators (itertools)

前端 未结 4 2195
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    I'm sorry to up this topic but after spending hours debugging a program trying to iterate over recursively generated cartesian product of generators. I can tell you that none of the solutions above work if not working with constant numbers as in all the examples above.

    Correction :

    from itertools import tee
    
    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):
                iterables_tee = list(map(tee, iterables[1:]))
                iterables[1:] = [it1 for it1, it2 in iterables_tee]
                iterable_copy = [it2 for it1, it2 in iterables_tee]
                for items in product(*iterable_copy):
                    yield (item, ) + items
    

    If your generators contain generators, you need to pass a copy to the recursive call.

提交回复
热议问题