First, iterators
Iterator can remember the object is a traverse position.
Iterator object began a visit from the first element of the collection until all the elements are accessed session is over. Iterator can only move forward not backward.
Strings, lists, tuples or objects can be used to create iterators.
1, iterator has two basic methods:
ITER () iterator object created
next () to the next element of the output iterator
from collections.abc import Iterator
S = '123'
IT1 = ITER (S)
Print (the isinstance (IT1, the Iterator)) # determines whether an object iterator object, output: True
Print (Next (IT1)) # Output:. 1
Print (Next (IT1)) # output: 2
Print (Next (IT1)) # output:. 3
#Print (Next (IT1)) # runs out of range error StopIteration
= Li [l, 2,3]
IT2 = ITER (Li)
Print (Next (IT2)) # Output:. 1
Print (Next (IT2)) # Output: 2
Print (Next (IT2)) # Output: 3
ITER = IT3 (Li)
# can be converted to a list as a list iterator
print (list (it3))
2, two ways iterator traversal: for, while
import sys
s = '123'
it1 = iter(s)
for i in it1:
print(i)
li = [1,2,3]
it2 = iter(li)
while True:
try:
print(next(it2))
except StopIteration:
sys.exit()
3, the iterator is used as a class: implement the __iter __ () and the __next __ () method in class
# 斐波那契数列
class Fibs:
def __init__(self):
self.a = 0
self.b = 1
def __next__(self):
self.a,self.b = self.b, self.a+self.b
return self.a
def __iter__(self):
return self
fibs = Fibs()
for f in fibs:
if f > 1000:
print(f)
break
Second, the generator
Builder is a special iterator uses the yield function is called generator, i.e. a generator is returned iterator functions only for an iterative operation.
1. Create generator
# 生成器函数
def Fibs(n):
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = Fibs (6) # f is an iterator
Print (Next (F))
Print (Next (F))
Print (Next (F)) # can Next
Print (F .__ Next __ ()) # can also be used _ _next__
Print (F .__ Next __ ())
Print (F .__ Next __ ())
Print (F .__ Next __ ())
'' 'Output:
0
. 1
. 1
2
. 3
. 5
. 8
' ''
for Fibs in F (. 6):
Print (F)
'' 'Output:
0
. 1
. 1
2
. 3
. 5
. 8
' ''
2, generator expression
Generating a list of expressions similar derivation formula, except the outermost layer of [] with (), the cycle is not performed immediately, but instead returns a generator.
r = (i*2 for i in range(5))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
'' 'Output:
0
2
. 4
. 6
. 8
' ''
'' 'May be traversed
for I in R & lt:
Print (I)
' ''
r2 = sum(i*2 for i in range(5))
print(r2)
'' 'Output:
20
' ''