author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tuto...
This paper addresses :http://www.showmeai.tech/article-detail/82
Statement : copyright , For reprint, please contact the platform and the author and indicate the source
Iteration is Python One of the most powerful features , Is a way to access collection elements .
An iterator is an object that remembers the traversal location .
The iterator object is accessed from the first element of the collection , Until all elements are accessed . Iterators can only move forward and not backward .
There are two basic ways to iterator :iter() and next().
character string , List or tuple objects can be used to create iterators :
list=[1,2,3,4]
it = iter(list) # Create iterator object
print(next(it)) # The next element of the output iterator 1
print(next(it)) # The next element of the output iterator 2
Iterator objects can use regular for Statement to traverse ( On-line python3 Environmental Science ):
l=['Baidu', 'ShowMeAI', 'google', 'ByteDance']
it = iter(l) # Create iterator object
for x in it:
print(x)
Execute the above procedure , The output is as follows :
Baidu
ShowMeAI
google
ByteDance
You can also use next() function ( On-line python3 Environmental Science ):
list=['Baidu', 'ShowMeAI', 'google', 'ByteDance']
it = iter(list) # Create iterator object
while True:
try:
print(next(it))
except StopIteration:
break
Execute the above procedure , The output is as follows :
Baidu
ShowMeAI
google
ByteDance
Using a class as an iterator requires implementing two methods in the class __iter__() And __next__() .
If you already know object-oriented programming , You know that every class has a constructor ,Python The constructor for is __init__(), It will execute when the object is initialized .
For more information, see :Python object-oriented
__iter__() Method returns a special iterator object , This iterator object implements __next__() Method and pass StopIteration The exception marks the completion of the iteration .
__next__() Method (Python 2 Is in the next()) The next iterator object is returned .
Create an iterator that returns a number , The initial value is 1, Gradually increasing 1( On-line python3 Environmental Science ):
class IterNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
num_class = IterNumbers()
iter_num = iter(num_class)
print(next(iter_num))
print(next(iter_num))
print(next(iter_num))
print(next(iter_num))
print(next(iter_num))
The execution output is :
1
2
3
4
5
StopIteration Exceptions are used to identify the completion of an iteration , To prevent infinite loops , stay __next__() Method, we can set to trigger after completing the specified number of cycles StopIteration Exception to end the iteration .
stay 10 Stop execution after iteration ( On-line python3 Environmental Science ):
class IterNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 10:
x = self.a
self.a += 1
return x
else:
raise StopIteration
num_class = IterNumbers()
iter_num = iter(num_class)
for x in iter_num:
print(x)
The execution output is :
1
2
3
4
5
6
7
8
9
10
stay Python in , Used yield The function of the is called the generator (generator).
Different from ordinary functions , A generator is a function that returns an iterator , Can only be used for iterative operations .
During the call generator run , Every encounter yield Function will pause and save all current running information , return yield Value , And next time next() Method to continue from the current location .
Call a generator function , Returns an iterator object .
The following example uses yield Realization of Fibonacci series ( On-line python3 Environmental Science ):
def fibonacci(n): # Generator function - Fibonacci
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f It's an iterator , Build returned by generator
while True:
try:
print(next(f))
except StopIteration:
break
Execute the above procedure , The output is as follows :
0
1
1
2
3
5
8
13
21
34
55
Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition
https://www.bilibili.com/vide...
The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can surf the Internet scientifically can also use google colab One click operation and interactive operation learning Oh !
This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :