An iterator
Python all objects
The object that can be used for looping is an iterative object.
Iterate objects: str, list, tuple, dict, set, range
Iterator: F1 file handle
Dir Prints all the action methods of the object:
s = ' python ' Print (dir (s))
Execution output:
[' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __ getattribute__ ', ' __getitem__ ', ' __getnewargs__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' _ _lt__ ', ' __mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __rmod__ ', ' __rmul__ ', ' _ _setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' capitalize ', ' casefold ', ' center ', ' count ', ' encode ', ' EndsWith ', ' expandtabs ', ' find ', ' format ', ' Format_map ', ' index ', ' isalnum ', ' isalpha ', ' isdecimal ', ' isdigit ', ' Isidentifier ', ' islower ', ' isnumeric ', ' isprintable ', ' isspace ', ' istitle ', ' isupper ', ' join ', ' ljust ', ' lower ', ' Lstrip ' ', ' Maketrans ', ' partition ', ' replace ', ' rfind ', ' rindex ', ' rjust ', ' rpartition ', ' rsplit ', ' Rstrip ', ' Split ', ' Splitline S ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill ']
What is an iterative object: An object that contains an __iter__ method internally is called an iterative object, and an iterative object follows an iterative protocol.
How to judge two kinds of ways:
The first type:
s = ' python ' Print (' __iter__ ' in Dir (s))
Execution output:
True
The second type:
From collections import iterable #此模块判断是否为可迭代对象l = [1,2,3,4]print (isinstance (l,iterable))
Execution output:
True
From collections Import Iterablel = [1, 2, 3, 4]print (Type (l)) print (Isinstance (l,list)
Execution output:
<class ' list ' >
True
Type can only judge what kind of
Isinstance judgment is more extensive, not only to determine the type, but also to determine whether it is possible to iterate
Iterators
An iterative object can be transformed into an iterator: an object that can be iterated over. __ITER__ ()--and iterators
Iterators contain not only __iter__, but also __next__. follows the iterator protocol.
L1 = [1,2,3]L1_OJB = l1.__iter__ () #迭代器print (L1_OJB)
Execution output:
<list_iterator Object at 0x000001987d5eb668>
Indicates that it is a list iterator object
L1 = [1,2,3]l1_obj = l1.__iter__ () #迭代器print (' __iter__ ' in Dir (l1_obj)) #是否含有__iter__方法print (' __next__ ' in Dir (L1) ) #是否含有__next__方法 here is the list of L1 that is given in Dir. Instead of L1_objprint (' __next__ ' in Dir (l1_obj))
Execution output:
True
False
True
From the results, it can be seen that l1_obj is an object that contains both __iter__ and __next__, so it is an iterator
Iterators use __next__ to get a value
L1 = [1,2,3]l1_obj = l1.__iter__ () # iterator print (l1_obj.__next__ ()) #获取一个元素print (l1_obj.__next__ ()) Print (l1_obj.__ next__ ()) print (l1_obj.__next__ ())
Execution Error:
1
Traceback (most recent):
2
3
File "e:/python_script/day13/iterator. Py", line 9, <module>
Print (l1_obj.__next__ ())
Stopiteration
If you take one more, you will get an error because the list has only 3 elements.
Use for loop mode
L1 = [1,2,3]L1_OJB = l1.__iter__ () #转换为迭代器for i in L1_OJB: print (i)
Execution output:
1
2
3
The internal mechanism of the For loop is performed using the __next__ method. Why is there no error? It has an exception handling mechanism inside it.
Summarize:
Containing only the __iter__ method, it is the object that can iterate
that contains the __iter__ and __next__ methods is the iterator
2 Ways to Judge Iterators:
The first type:
L1 = [1,2,3]L1_OJB = l1.__iter__ () #转换为迭代器print (' __iter__ ' in Dir (L1_OJB))
The second type:
L1 = [1,2,3]l1_obj = l1.__iter__ () from collections Import Iterableprint (Isinstance (l1_obj,iterable))
Returns true, which means that it is yes
Benefits of Iterators:
1. Save memory space.
2. The inertia mechanism is met.
3. Can not be repeated value, irreversible.
Irreversible, indicating that the value has been taken, can not be taken again, he can only take the next.
for processing mechanism
L2 = [1,2,3,4,5,6,7,8]for i in L2: print (i)
1. Convert an iterative object into an iterator
2. Internal use of the __next__ method to take the value
3. Using exception handling to deal with the error
The advantage of iterators is that they save memory space
Good programmers will consider memory optimizations, such as iterators
Use the while loop to specify that the list be traversed with the __next__ method
L2 = [1,2,3,4,5,6,7,8]l2_obj = l2.__iter__ () #1. Convert an iterative object to an iterator while True: try: i = l2_obj.__next__ () # Internally use the __next__ method to take the value print (i) except Exception: #运用了异常去处理报错 break
Try inside the code, there is an error, will not prompt the red text.
Exception can receive all the error, indicating when the error, how to deal with, here directly using break out of the loop
Interview questions:
Use the while loop to traverse a finite object
You can use the above code directly.
Two, generator
Generator: The generator is essentially an iterator
L = [1,2,3]l.__iter__ ()
#生成器的产生方式:
1. Builder function Constructs
2. Builder push-to-construct
3. Data type Conversion
123456 |
def func1(): print ( 111 ) print ( 222 ) print ( 333 ) return 666 print (func1()) |
Execution output:
111
222
333
666
To replace a function with a generator
Def func1 (): print (111) Print (222) Print (333) yield 666g = func1 () print (g)
Execution output:
<generator Object func1 at 0x0000023c67c2c3b8>
First: As long as the function has yield then he is not a function, but a generator
Second: G is called the Generator object.
Iterators, using __next__ to take values
Def func1 (): print (111) Print (222) Print (333) yield 666g = func1 () print (g.__next__ ()) Print (g.__ Next__ ())
Execute error
A __netxt__ corresponds to a yield. And there's one more.
Case:
Create 10000 sets of garments
A manufacturer directly produces 10000 sets of
Def func1 (): For I in range (1,10001): print (' Selected costume%d '% i) func1 ()
Post-Execution output:
Selected Clothing 1
。。。。。。
。。。。。。
Selected clothing 10000
I'll give you 50 sets.
Def func1 (): For I in range (1,10001): yield ' selected costume%d set '% IG = func1 () for I in Range (1,51): #我先生产 50 sets p Rint (g.__next__ ())
Post-Execution output:
Selected Clothing 1
。。。。。。
。。。。。。
Selected Clothing 50
The ultimate boss is 200 sets.
First 50 sets, then 150 sets.
Def func1 (): For I in range (1,10001): yield ' selected costume%d set '% IG = func1 () #先给你生产50套, pending follow-up the aftermath is giving you 150 sets for I in range (1,51): print (g.__next__ ()) for J in range: print (g.__next__ ())
Post-Execution output:
Selected Clothing 1
。。。。。。
。。。。。。
Selected clothing 200
For a list, the For loop starts at 0.
For the builder, it is made by the pointer, __next__ once, and the pointer forwards once. It can't start from scratch.
Must be executed in sequence.
The difference between a generator and an iterator
Iterators: There are built-in methods
Builder: Developer Customization
Send
Def generator (): print (123) content = yield 1 print (' ===== ', content) print (456) print (' * * * ', RET) Yieldg = Generator () ret = g.__next__ () print (' * * * ', ret) ret=g.send (' Hello ') print (' * * * ', ret)
123
1
===== Hello
55W
1
None
The effect of send to get the next value is basically the same as next
Just pass a data to the position of the previous yield when you get the next value
Considerations for using Send:
The first time you use the generator, you get the next value with next.
The last yield cannot accept external values.
Next, like the Send function, is performed once
Send can assign a value to the previous yield.
Contents of Dictation:
1. What is an iterative object and what is an iterator
For:
An object that contains the __iter__ method internally is called an iterative object.
The internal must have an __iter__ method and an object of the __next__ method, called an iterator.
2. How can iterative objects be transformed into iterators
For:
Convert to Iterators: Iterate over objects. __ITER__ ()--and iterators
For example:
L1 = [1,2,3]l1_obj = l1.__iter__ ()
3. How iterators are evaluated
For
Iterators using the __next__ () method
4. What is a generator and how do I write a generator? How does the generator take the value?
For:
Generator, which generates a container. In Python, one side loops, one side of the computational mechanism, called the generator
Generator Example:
The generator uses the __next__ () method to take a value, or a for loop
Python Full stack learning--day13 (iterator, generator)