Python Functional Programming - iterator
We already know that can act directly on for
the cycle of the data types are the following:
1, class is a collection of data types, such as list
, tuple
, dict
, set
, str
and the like;
2, a class generator
, comprising a generator and a band yield
generator function of.
These can act directly on the for
circulation of objects referred to as iterables: Iterable, may mean that the iteration can be traversed, it can be recycled.
May be used isinstance()
is determined whether an object is Iterable
an object:
>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance({}, Iterable)
True
>>> isinstance('abc', Iterable)
True
>>> isinstance((x for x in range(10)), Iterable)
True
>>> isinstance(100, Iterable)
False
The generator not only can act on a for loop, you can be next () function continues to call and returns the next value, until the last error thrown StopIteration said it could not continue to return the next value.
May be next () function call and return to the next target value continuously referred iterator: Iterator.
Builder is Iterator
an object, but list
, dict
, str
though Iterable
, is not Iterator
.
The list
, dict
, str
etc. Iterable
become Iterator
can use the iter()
function:
>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True
You might ask why list
, dict
, str
and other data types are not Iterator
?
This is because Python is Iterator
an object representation of the data stream, Iterator objects can be next()
invoked continue to function and returns the next data until the absence of data thrown StopIteration
error. This data stream can be seen as an ordered sequence, but we can not know in advance the length of the sequence, can only continue through the next()
realization of next-demand computing a data function, so the Iterator
calculations are inert, only need to return the next data it will be calculated.
Iterator
Even represent an infinite stream of data, such as all natural numbers. The list is never stored using all natural numbers.
to sum up
Who can act on for
circulating objects are Iterable
type;
Who can act on the next()
function objects are Iterator
types, which represents a sequence of lazy evaluation;
A set of data types, such as list
, dict
, str
and the like are Iterable
, but not Iterator
, however, can iter()
obtain a function Iterator
object.