What is the purpose in Python's itertools.repeat?

后端 未结 6 1890
我寻月下人不归
我寻月下人不归 2020-12-01 02:02

Every use I can think of for Python\'s itertools.repeat() class, I can think of another equally (possibly more) acceptable solution to achieve the same effect. For example:<

6条回答
  •  囚心锁ツ
    2020-12-01 02:10

    It's an iterator. Big clue here: it's in the itertools module. From the documentation you linked to:

    itertools.repeat(object[, times]) Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified.

    So you won't ever have all that stuff in memory. An example where you want to use it might be

    n = 25
    t = 0
    for x in itertools.repeat(4):
        if t > n:
            print t
        else:
            t += x
    

    as this will allow you an arbitrary number of 4s, or whatever you might need an infinite list of.

提交回复
热议问题