程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Graphical Python | iterators and generators

編輯:Python

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


1.Python iterator

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

(1) Create an iterator

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

(2)StopIteration

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

2. generator

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

3. Video tutorial

Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition

https://www.bilibili.com/vide...

Data and code download

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 :

  • Python Quick reference table

Expand references

  • Python course —Python3 file
  • Python course - Liao Xuefeng's official website

ShowMeAI Recommended articles

  • python Introduce
  • python Installation and environment configuration
  • python Basic grammar
  • python Basic data type
  • python Operator
  • python Condition control and if sentence
  • python Loop statement
  • python while loop
  • python for loop
  • python break sentence
  • python continue sentence
  • python pass sentence
  • python String and operation
  • python list
  • python Tuples
  • python Dictionaries
  • python aggregate
  • python function
  • python Iterators and generators
  • python data structure
  • python modular
  • python File read and write
  • python File and directory operations
  • python Error and exception handling
  • python object-oriented programming
  • python Namespace and scope
  • python Time and date

ShowMeAI A series of tutorials are recommended

  • The illustration Python Programming : From introduction to mastery
  • Graphical data analysis : From introduction to mastery
  • The illustration AI Mathematical basis : From introduction to mastery
  • Illustrate big data technology : From introduction to mastery


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved