Build a Basic Python Iterator

前端 未结 10 1057
南旧
南旧 2020-11-21 12:22

How would one create an iterative function (or iterator object) in python?

10条回答
  •  鱼传尺愫
    2020-11-21 12:57

    This is an iterable function without yield. It make use of the iter function and a closure which keeps it's state in a mutable (list) in the enclosing scope for python 2.

    def count(low, high):
        counter = [0]
        def tmp():
            val = low + counter[0]
            if val < high:
                counter[0] += 1
                return val
            return None
        return iter(tmp, None)
    

    For Python 3, closure state is kept in an immutable in the enclosing scope and nonlocal is used in local scope to update the state variable.

    def count(low, high):
        counter = 0
        def tmp():
            nonlocal counter
            val = low + counter
            if val < high:
                counter += 1
                return val
            return None
        return iter(tmp, None)  
    

    Test;

    for i in count(1,10):
        print(i)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    

提交回复
热议问题