Python -- iterator, python -- Generator
Iterator
1. iteratable objects
Can directly act on the for loop type:
These are collectively referred to as iteration objects, Iterable
You can use isinstance () to determine whether an object is Iterable:
True >>> from collections import Iterable >>> isinstance ([], Iterable) True >>> isinstance ({}, Iterable) True >>> isinstance (), Iterable) true >>> isinstance ("china", Iterable) True >>> isinstance (123, Iterable) # The number is not False >>> isinstance (range (10), Iterable) true >>> isinstance (x for x in range (10), Iterable) True
Note: The generator can not only act onforLoop, can also benext()The function is continuously called and the next value is returned until it is finally thrown.StopIterationAn error indicates that the next value cannot be returned.
Ii. iterator
Iterator ):Can benext()The object that calls the function and continuously returns the next value is called the iterator:Iterator.
You can use isinstance () to determine whether an object is an Iterator object:
>>> isinstance([],Iterator)False>>> isinstance({},Iterator)False>>> isinstance((),Iterator)False>>> isinstance((x for x in range(10)),Iterator)True
Generators are all Iterator objects, but they are not Iterator although list, dict, tuple, and string are also Iterable ).
Iii. iter () function
We can use the iter () function to convert an Iterable object into an Iterator)
Setlist,dict,strAnd so onIterableChangeIteratorAvailableiter()Function:
>>> isinstance(iter([]),Iterator)True>>> isinstance(iter({}),Iterator)True>>> isinstance(iter(()),Iterator)True>>> isinstance(iter("sssss"),Iterator)True
You may ask whylist,dict,strAnd other data types are notIterator?
This is because PythonIteratorThe object represents a data stream, and the Iterator object can benext()The function calls and continuously returns the next data until no data is returned.StopIterationError. We can regard this data stream as an ordered sequence, but we cannot know the length of the sequence in advance and can only continue to pass throughnext()Function implementation calculates the next data as needed, soIteratorThe computation of is inert and will only be calculated when the next data needs to be returned.
IteratorIt can even represent an infinitely large data stream, such as all natural numbers. However, using list is never possible to store all natural numbers.
Iv. Loop of iteratable objects
G = (x for x in range (5) for I in g: print (I) # actually equivalent to it = iter ([0, 1, 2, 3, 4]) # print (type (it) while True: try: x = next (it) print (x) Doesn't StopIteration: break
V. Summary