Python Functional Programming - iterator

Python Functional Programming - iterator

We already know that can act directly on forthe cycle of the data types are the following:

1, class is a collection of data types, such as list, tuple, dict, set, strand the like;

2, a class generator, comprising a generator and a band yieldgenerator function of.

These can act directly on the forcirculation 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 Iterablean 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 Iteratoran object, but list, dict, strthough Iterable, is not Iterator.

The list, dict, stretc. Iterablebecome Iteratorcan use the iter()function:

>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True

You might ask why list, dict, strand other data types are not Iterator?

This is because Python is Iteratoran 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 StopIterationerror. 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 Iteratorcalculations are inert, only need to return the next data it will be calculated.

IteratorEven 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 forcirculating objects are Iterabletype;

Who can act on the next()function objects are Iteratortypes, which represents a sequence of lazy evaluation;

A set of data types, such as list, dict, strand the like are Iterable, but not Iterator, however, can iter()obtain a function Iteratorobject.

Guess you like

Origin www.cnblogs.com/Kwan-C/p/11530055.html