Python for loop data type

For loop can act directly on the type of data are the following:

A class is a collection of data types, such as a list, tuple, dict, set, str, etc.

One is the generator, comprising a generator and a generator function with a yield of

These can act directly on the object for circulation collectively referred to as iterables: Iterable

Can use the isinstance () determines whether an object to be Iterable objects

>>> 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

So here we talk about iterators

Iter implements a method is iterative object, the object is a method to achieve next iterator;

May be next () function call and return to the next target value continuously referred iterator: Iterator.

Can use the isinstance () determines whether an object is Iterator objects:

>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('abc', Iterator)
False

Builder is Iteratoran object, but list, dict, strthough Iterable(可迭代对象), is not Iterator(迭代器).

The list, dict, stretc. IterablebecomeIterator can use the iter()function :

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

Why list, dict, strand other data types are not Iterator?

This is because Python is Iteratoran object representation of the data flow , 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.

 

Guess you like

Origin blog.csdn.net/bl128ve900/article/details/94395839
Recommended