python--yield generator and return comparison

 

Iteration is one of Python's most powerful features and a way to access collection elements.

An iterator is an object that can remember the position of traversal.

The iterator object is accessed from the first element of the collection until all elements are accessed. The iterator can only go forward without going backward.

Iterator has two basic methods: iter ()  and  next () .

Generators are special iterators

def gen_yield():
    for i in range(1,10):
        for j in range(1,10):
            yield  i+j
            # return i+j

if __name__ == '__main__':
    aa = gen_yield()
    print(aa.__next__())
    print(aa.__next__())
    print(aa.__next__())
    print(aa.__next__())
    print(aa.__next__())
    print(aa.__next__())

Both yield and return have the effect of the return value, but the difference is that yield will remember the position of the current iteration, and return will not

If you still cannot understand the difference between the two,

def test_yield():
    for i in [1,2,3]:
        yield i

def test_return():
    for i in [1,2,4]:
        return i

if __name__ == '__main__':
    test_yield_obj = test_yield()
    print('这里测试yield')
    print(test_yield_obj.__next__())   # 1
    print(test_yield_obj.__next__())   # 2
    print(test_yield_obj.__next__())   # 3

    print ( ' Here is the test return ' )
     print (test_return ()) # 1
     print (test_return ()) # 1
     print (test_return ()) # 1

 

Guess you like

Origin www.cnblogs.com/lutt/p/12723154.html