Python 生成器常用场景一 取代普通迭代器

在上一篇文章

https://blog.csdn.net/nvd11/article/details/138738472

已经简单介绍了生成器 是 一种特殊的迭代器

而的确, 大部分普通的迭代器是可以被生成器取代的, 以达到简化代码的目的。

使用迭代器的例子

我们找回之前介绍迭代器用到的link list 例子:

https://blog.csdn.net/nvd11/article/details/138736024

里面的link list 保护了3个类

Node 类:
python 复制代码
class Node:
    def __init__(self, value):
        self._value = value
        self._next = None
    
    @property
    def value(self):
        return self._value
    
    @property
    def next(self):
        return self._next
    
    @next.setter
    def next(self, next):
        self._next = next

    @value.setter
    def value(self, value):
        self._value = value
LinkList类 它是iterable 可迭代对象
py 复制代码
from loguru import logger

from src.iterator.sample_link_list.link_list_iterator import LinkListIterator
from src.iterator.sample_link_list.node import Node


class LinkList:
    def __init__(self, first) -> None:
        node = Node(first)
        _first_node = node
        _last_node = node

    def __init__(self, *values) -> None:
        if len(values) < 1:
            raise ValueError("At least one node is required")
        self._first_node = Node(values[0])
        current = self._first_node
        for i in range(1, len(values)):
            current.next = Node(values[i])
            current = current.next
        self._last_node = current

    def __iter__(self):
        return LinkListIterator(self._first_node)

    # to print all nodes's value but not nodes themselves
    def print_nodes(self):
        current = self._first_node
        while current:
            logger.info(current.value)
            current = current.next

    def get_length(self):
        current = self._first_node
        count = 0
        while current:
            count += 1
            current = current.next
        return count

    def append(self, value):
        if self.get_length() == 0:
            self._first_node = Node(value)
            self._last_node = self._first_node
        else:
            self._last_node.next = Node(value)
            self._last_node = self._last_node.next
        

        

可以见到, 它的__iter__ 方法返回1个迭代器对象

LinkListIterator(self._first_node)

所以我们还需要被编写这个迭代器的类代码:

它要实现__next__ 方法

python 复制代码
class LinkListIterator:
    def __init__(self, _first_node) -> None:
        self._current_node = _first_node

    def __iter__(self):
        return self
    
    def __next__(self):
        if not self._current_node:
            raise StopIteration
        current = self._current_node
        self._current_node = current.next
        return current.value

改成用生成器

一旦我们改用生成器, 则只需要让LinkList 这个interable 的__iter__ 方法变成1个生成器即可

如何让1个方法/函数变成1个生成器, 上一篇文章讲过, 就是使用yield 关键字啊

修改后的代码如下:

python 复制代码
    def __iter__(self):
        current = self._first_node
        while current:
            yield current.value
            current = current.next
        return

注意这个生成器方法默认是没有参数的

所以它第一元素是 self_first_node

之后yield 当前node 的value出去 , 然后不断让当前元素变成下个原属就好

而这时 原来了的LinkListIterator 就不再需要,大大简化了代码!

相关推荐
蒋星熠3 分钟前
破壁者指南:内网穿透技术的深度解构与实战方法
网络·数据库·redis·python·websocket·网络协议·udp
shizidushu9 分钟前
使用 Pyinstaller 打包 PPOCRLabel
python·pyinstaller
Q_Q196328847542 分钟前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php
Rhys..1 小时前
.gitignore文件的作用及用法
python·github
IT学长编程1 小时前
计算机毕业设计 基于深度学习的酒店评论文本情感分析研究 Python毕业设计项目 Hadoop毕业设计选题 机器学习选题【附源码+文档报告+安装调试】
hadoop·python·深度学习·机器学习·数据分析·毕业设计·酒店评论文本情感分析
~-~%%2 小时前
Moe机制与pytorch实现
人工智能·pytorch·python
深耕AI2 小时前
【PyTorch训练】为什么要有 loss.backward() 和 optimizer.step()?
人工智能·pytorch·python
0_0梅伊阁诗人3 小时前
Django ORM 模型
开发语言·数据库·笔记·python·oracle·django
Genevieve_xiao3 小时前
【dl】python基础 深度学习中需要用到的python基础
python·深度学习
m0_578267863 小时前
从零开始的python学习(九)P142+P143+P144+P145+P146
笔记·python·学习