python- iterables / iterator / generator


# Iterables iterable 

Can be for / the object's class there def __iter __ (self) Method


for principle:

for i in list1:
print(i)


iterable=list1.__iter__()
while True:
try:
i=iterable.next()
print(i)
except StopIteration:
break

 

 

# Iterator iterator object
can call the next () method

iterator class class name:
DEF the __init __ (Self, aggregate object):
. Self polymerization of aggregated objects target =

__ the __next DEF (Self):
IF there is no element:
The raise the StopIteration
return the element to the polymerization


SkillIterator class:
"" "
skills iterator
" ""

def __init__(self, data):
self.__target = data
self.__index = -1

__ the __next DEF (Self):
IF len (Self .__ target) - Self .__. 1 == index:
The raise the StopIteration ()
# returns the next data
Self .__. 1 = index +
return target Self .__ [Self .__ index]

 

 

Builder: iterables conjunction iterator +

 


Built-in generator function #python
the enumerate
for variables in enumerate (iterables): # variable is a tuple (index elements)
Statement

for the index, the elements in enumerate (iterable):
statement


ZIP
for Item in ZIP (iterables 1, 2 ... iterable.): # variable is a tuple (Object element 1, element 2 objects ....) prevail in the shortest iterable
statement

 

Generator expressions:
variable = (variable in the expression for iterables [if truth expression])

 

 

Guess you like

Origin www.cnblogs.com/chenlulu1122/p/11921818.html