Skip to Content
《高性能 Python》第二版
book

《高性能 Python》第二版

by Micha Gorelick, Ian Ozsvald
May 2025
Intermediate to advanced
468 pages
6h 20m
Chinese
O'Reilly Media, Inc.
Content preview from 《高性能 Python》第二版

第 5 章 迭代器和生成器

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

当许多有其他语言经验的人开始学习 Python 时,他们会对for 循环符号的不同感到吃惊。 也就是说,不写

# Other languages
for (i=0; i<N; i++) {
    do_work(i);
}

它们被引入一个名为range 的新函数:

# Python
for i in range(N):
    do_work(i)

在 Python 示例代码中,我们似乎在调用一个函数range ,它创建了for 循环继续所需的所有数据。直观地说,这可能是一个相当耗时的过程--如果我们要循环遍历 1 到 100,000,000 的数字,那么我们就需要花费大量时间来创建数组!然而,这正是生成器发挥作用的地方:从本质上讲,生成器允许我们懒散地评估这些函数,因此我们可以获得这些特殊用途函数的代码可读性,而不会对性能造成影响。

为了理解这一概念,让我们实现一个函数,通过填充列表和使用生成器来计算几个斐波那契数字:

def fibonacci_list(num_items):
    numbers = []
    a, b = 0, 1
    while len(numbers) < num_items:
        numbers.append(a)
        a, b = b, a+b
    return numbers

def fibonacci_gen(num_items):
    a, b = 0, 1
    while num_items:
        yield a  1
        a, b = b, a+b
        num_items -= 1
1

该函数将yield 多个值,而不是返回一个值。 这就将这个看似普通的函数变成了一个生成器,可以反复轮询以获取下一个可用值。

首先要注意的是, fibonacci_list 实现必须创建并存储所有相关斐波那契数字的列表。 因此,如果我们想要 10,000 个序列的数字,函数将对numbers 列表进行 10,000 次追加(正如我们在第 3 章中讨论过的,追加会产生开销),然后返回。

另一方面,生成器能够 "返回 "许多值。 每当代码运行到yield 时,函数就会输出其值,而当请求另一个值时,函数就会恢复运行(保持先前状态)并输出新值。 当函数运行到终点时, StopIteration 异常,表明给定的生成器没有更多的值。 因此,尽管两个函数最终必须进行的计算次数相同,但fibonacci_list 版本的前一个循环使用的内存要多 10,000 倍(或num_items 倍)。

有了这些代码,我们就可以分解使用我们实现的fibonacci_listfibonacci_genfor 循环。在 Python 中,for 循环要求我们要循环的对象支持迭代。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

《学习 Python》第 5 版

《学习 Python》第 5 版

Mark Lutz
ppk on JavaScript

ppk on JavaScript

Peter-Paul Koch

Publisher Resources

ISBN: 9798341657946