Python study notes: iterator (Iterator) Comments

An object (the Iterable) available iterations
1, definition: can be used directly in the circulating type of data, such as list, tuple, dict, set, str, there Generator (generator),
and with a function of yield, which can be directly For use in circulation collectively iterables (the iterable)
from Collections Import the Iterable
 Print (the isinstance ([], the Iterable))
 Print (the isinstance ((), the Iterable))
 Print (the isinstance ({}, the Iterable))
 Print (the isinstance ( " ABC " , the Iterable))
 Print (the isinstance (( X for X in Range (10)), the iterable)) # generator is iterables 
Print (the isinstance (10, the iterable)) # number is not iterables

Second, the iterator (the Iterator)

. 1, defined: not only can be used in the generator cycle, but also () call returns the next value constantly with the next, until the burst StopIteration exception,
2, and iterator iterables and differences: iterator and iterable not the same concept, the difference is whether there is the next function (you can use dir (object) to see all the available functions of this object).
from Collections Import the Iterator Print (the isinstance ([], the Iterator))
 Print (the isinstance ((), the Iterator))
 Print (the isinstance ({}, the Iterator))
 Print (the isinstance ( " ABC " , the Iterator))
 Print (the isinstance (( X for X in Range (10)), the iterator))   # generator iterators 
Print (the isinstance (10, the iterator))   # number is not iterator object

Third, the conversion may be between the object and iteration iterator

1, using ITER () function to convert iterables iterator.
list1 = iter([1,2,3,4,5])
print(list1.__next__())
print(list1.__next__())
   2, why, like list, string, tuple such iterable is not an iterator? 
Because these data structures are already existing data assigned to them, and iterators are lazy evaluation of program flow, he even no data, so iterables can only represent a limited number of elements, and iterators can even represent the entire set of natural numbers .

Four, python iterator function has a lot of shadows, give some examples of the built-in iterator

1, cycle used range (), in fact, an iterator, such as range (10000), instead of generating a set of elements 10000, a built next function, individually generated.
2, when file.redelines file called (), return a list, for line in file: is the iterator forward line by line, is built next function

V. Summary: iterator is a concept, in fact, generate applicators.



Guess you like

Origin www.cnblogs.com/tangwei-fuzhou/p/12669087.html