Correct understanding of python iterators and generators

  • 2021-11-10 10:17:41
  • OfStack

Directory 1. Iterator 2. Generator 3. Generator Function 3.1, zip (Iterable Object 1, Iterable Object 2...) 3.2, enumerate (iterable [, start])

1. Iterators

Iterators are the objects returned by iter (Iterable Object Function), which are composed of one iterator.

You can use the next () function to get the data of an iterable object

Iteration is one way to access the elements of a collection (because collections are unordered, they cannot be indexed), naxt (collections),

The iterator object is accessed from the first element of the collection until all the elements are accessed, and the iterator can only move forward and not backward

Iterator is an object that can remember the position of traversal. Iterators can only be produced one by one. There is no such value in the first 1 second, and it will not be generated until next ()

Iterators have two basic methods: iter () and next ()

iter () generates 1 iterator next () fetches and writes 1 record from the iterator. If it cannot fetch and writes 1 record, it triggers StopIteration exception

Ordered sequence: String, list, tuple objects can be used to create iterators


L = [1,2,3,4]
it = iter(L)    # Create an iterator object 
print(next(it)) # Write of output iterator 1 Objects 
print(next(it))

Iterator objects are traversed using for statements


li = [5,6,7,8]
it = iter(li)
for x in it: 
    print(x,end = ' ')

Iterator objects are traversed using while statements


lis = [7,8,9,0]
it = iter(lis)
while True:
    try:
        print(next(it))
    except StopIteration:
        break

2. Generator

In python, the function that uses yield is called the generator (generator). This function returns 1 generator object when called

The generator is a function that returns an iterator. The generator generates an iterator object, which can only be used for iterative operations

The generator can stop the function and think about it. It's very casual. The data in the first 1 second doesn't exist at all. This 1 second is calculated

In the process of calling the generator to run, every time yidld is encountered, the function will stop and return the value of yield, which is equivalent to print returning the value of print

And continue from the current position the next time the next () method is executed or the loop is written (continue to print the next value)

Generator is used in function, will use the function as generator, the function gives 1 value, and the main function calls 1 value

A generator call to return triggers an StopIteration exception

Generating Fibonacci sequence by common method


def fun(n):
    a,b,c = 0,1,0
    while c<n:
        print(b)    #  Print Fibonaccet Sequence 
        a,b = b,a+b
        c +=1

fun(10)

Generating Fibonacci sequence by generator method


def fun(n):
    a,b,c = 0,1,0
    while c<n:
        yield b     #  Generator 
        a,b = b,a+b
        c +=1

# print(fun(10))# <generator object fun at 0x000001ED43A48A40>
t = fun(10)    # t Yes 1 Iterators that are returned by the generator to generate 
print(next(t))  # 1
print(next(t))  # 1
print(" You can insert code in the middle ")  #  You can insert code in the middle 
print(next(t))  # 2
print(next(t))  # 3

for i in t:
    print(i)
# 8
# 13
# 21
# 34
# 55

print(fun(10))

# < generator object fun at 0x000001ED43A48A40 >   

# This is a piece of memory, you need to use the function to access the value inside, next (fun (10))

Generator expression:

Syntax: (Expression for Variable in Iterable Object [if Truth Expression]) Content in [] can be omitted Function: Generate a new generator in the form of derivation. When you want to get the value, you should change iter into an iterator and use next to get the value Advantages: It does not occupy memory space

Iteration tool function: generate 1 iterable object


gen = (x**2 for x in range(1, 4))
it = iter(gen)  #  Conversion generator 
next(it)    # 1
next(it)    # 4
next(it)    # 9
next(it)    # StopIteration

3. Generator functions

3.1. zip (Iterable Object 1, Iterable Object 2...)

Returns 1 zip object, which is used to generate tuples, and the number of tuples is determined by the smallest iterable object


numbers = [10086,10000,10010,95586]
names = [' China Mobile ',' China Unicom ',' China Telecom ']
for t in zip(numbers,names):
    print(t)

#(10086, ' China Mobile ')
#(10000, ' China Unicom ')
#(10010, ' China Telecom ')

Custom zip function


def myzip(iter1,iter2):
    it1 = iter(iter1)   #  Take out 1 Iterators 
    it2 = iter(iter2)
    while True:
        a = next(it1)
        b = next(it2)
        yield (a,b)

numbers = [10086,10000,10010,95586]
names = [' China Mobile ',' China Unicom ',' China Telecom ']
for t in myzip(numbers,names):
    print(t)
# (10086, ' China Mobile ')
# (10000, ' China Unicom ')
# (10010, ' China Telecom ')

3.2. enumerate (iterable [, start])

Generates an indexed enumeration object that returns an index-value pair of iteration type (index, value) with a zero-based default index or an start binding


names = [' China Mobile ', ' China Telecom ', ' China Unicom ']
for x in enumerate(names):  # Generate iterator 
    print(x)
def myenumerate(iterable):
    it = iter(iterable)
    i = 0
    while True:
        a = next(it)
        yield(i,a)
        i += 1
#(0, ' China Mobile ')
#(1, ' China Telecom ')
#(2, ' China Unicom ')

The above is the correct understanding of python iterator and generator details, more information about python iterator and generator please pay attention to other related articles on this site!


Related articles: