python - iterator

First, the iterator (Iterator)

An iterator is a traverse position of the object can remember.

It starts from the first element of the collection until the collection of all the elements are accessed session is over.

Strings, lists, dictionaries, tuples, collections are iterable. (But not necessarily iterators)

Iterator has two basic methods:

iter (): used to create an iteration object (after creating before proceeding for ... in ... iteration)

next (): used to access the next element in the iterator

next () is one-way, one can only get one element, after obtaining the last element to stop, only to traverse forward, not backward

 

Iterator in processing large amounts of data, even with a load data fast, small memory of the advantages of unlimited data, widely used in Python.

 

from collections import Iterable # iterables 
from collections import Iterator # iterators


# ---------------------------------- -------
# iterator (iterator)
# ------------------------------------ -----
# loop through the collection of elements used for
cities = [ 'Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen']
for City in Cities:
Print (City)
Print ()

t = (100, 200, 300)
S = { 'A', 'B', 'C'}
D = { 'A': 100, 'B': 200 is, 'C': 300}
C = 'Nanjing'

# determines whether iterables
Print (the isinstance (Cities, the Iterable))
Print (the isinstance (T, the Iterable))
Print (the isinstance (S, the Iterable))
Print (the isinstance (D, the Iterable))
Print (the isinstance (C,The Iterable))
Print ()

# determines whether the iterator (the object is a non-iterative iterator)
Print (the isinstance (Cities, the Iterator))
Print (the isinstance (T, the Iterator))
Print (the isinstance (S, the Iterator))
Print (the isinstance (D, the Iterator))
Print (the isinstance (C, the Iterator))

# iterators access list of
cities = [ 'Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen']
i = iter (Cities) # create iterator object (available traverse)
# conventional for statement to traverse
for city in i:
Print (City)
Print ()

Cities = [ 'Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen']
i = iter (Cities)
# use the next () function to traverse, equivalent to the for ... in loop
True the while:
the try:
Print (the Next (i))
the except StopIteration:
Print ( "stop the iteration")
BREAK

Guess you like

Origin www.cnblogs.com/Teachertao/p/11229186.html