python- iterators, generator

Generator belonging iterator

Suitable iterator object: list, dict, tuple, set, str

Not suitable iteration object: int, float, bool

Iterator example :

a = [0,1,2,3]

ITER (A) with a # ITER () method to generate iterables

Print ( next (A)) with a # next to the query, until out of range

 

Whether the interpretation of objects that meet iterations example :

from collections import Iterable

a = [0,1,2,3]

b = 123

Print (isinstance (A, Iterable )) # use isinstance function to determine, this result is True, in line with the iterative

Print (isinstance (A, Iterable )) # above, this result is Flase, does not meet iterations

 

Generator Examples :

a = (i for i in range (1000000)) # wants a list of the formula [] into (), a case of type generators (Generator)

print (next (a)) # use next () to query

 

Evolved to function generator :( return to the yield change)

example:

DEF F (n-): 
for I in Range (n-):
the yield I
     Print ( 'OKOK')

A = F (. 5) # define a variable to receive the generator return value
print (next (a)) # running reached after the yield will stop, down is not executed, so only print 0
print (next (A)) # program execution begins at the breakpoint yield, so the first print 'OKOK', in 1 print, then stopping
print (next (A))
Print (Next (A))
Print (Next (A))
# Print (Next (A))

, or for loop to print (all at once printed, preventing next () method of range error)
for Range in I (A):
  Print (I)




Guess you like

Origin www.cnblogs.com/lovesix/p/11902207.html