Written for Python programming masters 2: Iterators
Python Tutorial column introduces iterators used in programming.
Related free learning recommendations: python tutorial (video)
How to implement iterable objects and iteration Iterator object
The iterator pattern is a classic software design pattern. Now many programming languages have built-in this design pattern. Among Python's primitive data types, those that can be used for for loops are iterable types. Of course, you can also use the iter function to obtain the corresponding iterator and then traverse the object. For example, the following code:
l = [1, 3] # 可迭代对象 __iter__t = iter(l) #获取迭代器对象print(t.__next__()) print(t.__next__())# print(t.__next__()) # 报异常复制代码
To implement an iterable object, you must first implement the corresponding iterator object. To implement an iterator in Python, you only need to implement the __next__ method. However, the Iterator class in the collections package defines the __next__ method as an abstract method. The author believes that in view of the readability of the program, you may wish to inherit the Iterator class when implementing an iterator.
from random import samplefrom collections import Iterable, Iteratorclass WeatherIterator(Iterator): def __init__(self, cities): self.cities = cities self.index = 0 def getWeather(self, city): return (city, sample(['sun','wind','yu'], 1)[0]) def __next__(self): if self.index == len(self.cities): raise StopIteration city = self.cities[self.index] self.index += 1 return self.getWeather(city)复制代码
To implement an iterable object, you only need to implement the __iter__ method. Similarly, the Iterable class in the collections package also defines the __iter__ method as an abstract class.
from collections import Iterableclass WeatherIterable(Iterable): def __init__(self, cities): self.cities = cities self.index = 0 def __iter__(self): return WeatherIterator(self.cities)复制代码
This way you can use a for loop to iterate.
for weather in WeatherIterable(['北京', '上海', '广州']): print(weather)复制代码
Introduction to generator
First look at the following code:
def gen(): print("step 1") yield 1 print("step 2") yield 2 print("step 3") yield 3复制代码
The return value of the above gen function is a generator object.
g = gen() g.__next__() print(g.__next__()) print(g.__next__())复制代码
As shown in the above code, every time the __next__ method of the generator is called, it will execute a gen function until it encounters the yield keyword, and return what follows. Therefore, a generator can be understood as a function that can be interrupted.
Note: Generator objects are also iterable objects.
for x in g: print(x)复制代码
How to use a generator function to implement an iterable object
By implementing the __iter__ method as a generator function, you can implement an iterable object.
class PrimeNumbers: def __init__(self, start, end): self.start = start self.end = end def isPrimeNum(self, k): #判断是否是素数 if k < 2: return False for i in range(2, k): if k % i == 0: return False return True def __iter__(self): for k in range(self.start, self.end + 1): if self.isPrimeNum(k): yield kfor num in PrimeNumbers(2, 100): print(num)复制代码
How to perform reverse iteration and how to implement reverse iteration
The iter function can obtain the forward iterator of the iterable object, and the reversed function can obtain the reverse iterator of the iterable object. iterator.
l = [1, 2, 3, 4, 5]for x in reversed(l): print(x)复制代码
To implement reverse iteration, just implement the __reversed__ method.
class FloatRange: def __init__(self, start, end, step=0.1): self.start = start self.end = end self.step = step def __iter__(self): t = self.start while t <= self.end: yield t t += self.step def __reversed__(self): t = self.end while t >= self.start: yield t t -= self.stepfor x in FloatRange(1.0, 4.0, 0.5): print(x)for x in reversed(FloatRange(1.0, 4.0, 0.5)): print(x)复制代码
How to perform slicing operations on iterators
The islice function in the itertools package can perform slicing operations on iterable objects.
from itertools import islicefor x in islice(FloatRange(1.0, 4.0, 0.5), 2, 5): print(x)复制代码
How to iterate multiple iterable objects in a for statement
Use the zip method to form a tuple of corresponding elements.
for w, e, m in zip([1, 2, 3, 4], ('a', 'b', 'c','d'), [5, 6, 7, 8]): print(w, e, m)复制代码
Use the chain function in the itertools package to concatenate multiple iterable objects. Use the zip method to form a tuple of corresponding elements.
from itertools import chainfor x in chain([1, 2, 3, 4], ('a', 'b', 'c','d')): print(x)复制代码
The above is the detailed content of Written for Python programming masters 2: Iterators. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use iterators and recursive algorithms to process data in C# requires specific code examples. In C#, iterators and recursive algorithms are two commonly used data processing methods. Iterators can help us traverse the elements in a collection, and recursive algorithms can handle complex problems efficiently. This article details how to use iterators and recursive algorithms to process data, and provides specific code examples. Using Iterators to Process Data In C#, we can use iterators to iterate over the elements in a collection without knowing the size of the collection in advance. Through the iterator, I

How to use Python to write and execute scripts in Linux In the Linux operating system, we can use Python to write and execute various scripts. Python is a concise and powerful programming language that provides a wealth of libraries and tools to make scripting easier and more efficient. Below we will introduce the basic steps of how to use Python for script writing and execution in Linux, and provide some specific code examples to help you better understand and use it. Install Python

Usage and code examples of the sqrt() function in Python 1. Function and introduction of the sqrt() function In Python programming, the sqrt() function is a function in the math module, and its function is to calculate the square root of a number. The square root means that a number multiplied by itself equals the square of the number, that is, x*x=n, then x is the square root of n. The sqrt() function can be used in the program to calculate the square root. 2. How to use the sqrt() function in Python, sq

Teach you to use Python programming to implement the docking of Baidu's image recognition interface and realize the image recognition function. In the field of computer vision, image recognition technology is a very important technology. Baidu provides a powerful image recognition interface through which we can easily implement image classification, labeling, face recognition and other functions. This article will teach you how to use the Python programming language to realize the image recognition function by connecting to the Baidu image recognition interface. First, we need to create an application on Baidu Developer Platform and obtain

Python programming to analyze the coordinate conversion function in Baidu Map API document Introduction: With the rapid development of the Internet, the map positioning function has become an indispensable part of modern people's lives. As one of the most popular map services in China, Baidu Maps provides a series of APIs for developers to use. This article will use Python programming to analyze the coordinate conversion function in Baidu Map API documentation and give corresponding code examples. 1. Introduction In development, we sometimes involve coordinate conversion issues. Baidu Map AP

How to write PCA principal component analysis algorithm in Python? PCA (Principal Component Analysis) is a commonly used unsupervised learning algorithm used to reduce the dimensionality of data to better understand and analyze data. In this article, we will learn how to write the PCA principal component analysis algorithm using Python and provide specific code examples. The steps of PCA are as follows: Standardize the data: Zero the mean of each feature of the data and adjust the variance to the same range to ensure

How to do image processing and recognition in Python Summary: Modern technology has made image processing and recognition an important tool in many fields. Python is an easy-to-learn and use programming language with rich image processing and recognition libraries. This article will introduce how to use Python for image processing and recognition, and provide specific code examples. Image processing: Image processing is the process of performing various operations and transformations on images to improve image quality, extract information from images, etc. PIL library in Python (Pi

How to write a program in Python to obtain map tiles in Baidu Map API? Map tiles are the basic elements that make up a map. By dividing the map into small independent images, you can achieve faster map loading and display. Baidu Map API provides rich map tile data. This article will introduce how to use Python to obtain map tiles in Baidu Map API and give code examples. Obtaining the map tiles of Baidu Map API requires using the key (ak) provided by the interface. Therefore, you first need to use Baidu Map
