Does itertools.product evaluate its arguments lazily?

前端 未结 3 1126
感情败类
感情败类 2020-12-03 22:49

The following never prints anything in Python 3.6

from itertools import product, count

for f in product(count(), [1,2]): 
    print(f)

Ins

3条回答
  •  旧时难觅i
    2020-12-03 23:16

    The issue seems to be that product never returns an iterator

    No, product is already "lazy".

    The issue is thatcount() counts to infinity. From count's docs:

    Equivalent to:

    def count(start=0, step=1):
        # count(10) --> 10 11 12 13 14 ...
        # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
        n = start
        while True:
            yield n
            n += step
    

    You code is basically the same as doing:

    def count():
        i = 0
        while True:
            yield i
            i += 1
    
    count()
    

提交回复
热议问题