Table of Contents
How to implement iterable objects and iteration Iterator object
Introduction to generator
How to use a generator function to implement an iterable object
How to perform reverse iteration and how to implement reverse iteration
How to perform slicing operations on iterators
How to iterate multiple iterable objects in a for statement
Home Backend Development Python Tutorial Written for Python programming masters 2: Iterators

Written for Python programming masters 2: Iterators

Nov 04, 2020 pm 05:19 PM
python programming Iterator

Python Tutorial column introduces iterators used in programming.

Written for Python programming masters 2: Iterators

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__()) # 报异常复制代码
Copy after login

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)复制代码
Copy after login

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)复制代码
Copy after login

This way you can use a for loop to iterate.

for weather in WeatherIterable(['北京', '上海', '广州']):
    print(weather)复制代码
Copy after login

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复制代码
Copy after login

The return value of the above gen function is a generator object.

g = gen()
g.__next__()
print(g.__next__())
print(g.__next__())复制代码
Copy after login

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)复制代码
Copy after login

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)复制代码
Copy after login

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)复制代码
Copy after login

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)复制代码
Copy after login

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)复制代码
Copy after login

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)复制代码
Copy after login

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)复制代码
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use iterators and recursive algorithms to process data in C# How to use iterators and recursive algorithms to process data in C# Oct 08, 2023 pm 07:21 PM

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 for scripting and execution in Linux How to use Python for scripting and execution in Linux Oct 05, 2023 am 11:45 AM

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 of sqrt() function in Python Usage of sqrt() function in Python Feb 21, 2024 pm 03:09 PM

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 how to use Python programming to realize the docking of Baidu image recognition interface and realize the image recognition function. Teach you how to use Python programming to realize the docking of Baidu image recognition interface and realize the image recognition function. Aug 25, 2023 pm 03:10 PM

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 documentation Python programming to analyze the coordinate conversion function in Baidu Map API documentation Aug 01, 2023 am 08:57 AM

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? How to write PCA principal component analysis algorithm in Python? Sep 20, 2023 am 10:34 AM

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 How to do image processing and recognition in Python Oct 20, 2023 pm 12:10 PM

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? How to write a program in Python to obtain map tiles in Baidu Map API? Jul 31, 2023 pm 04:21 PM

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

See all articles