Home  >  Article  >  Backend Development  >  Written for Python programming masters 2: Iterators

Written for Python programming masters 2: Iterators

coldplay.xixi
coldplay.xixiforward
2020-11-04 17:19:112009browse

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

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!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete