Skip to Content
流畅的Python(第2版)
book

流畅的Python(第2版)

by Luciano Ramalho
April 2023
Intermediate to advanced
769 pages
25h 16m
Chinese
Posts & Telecom Press
Content preview from 流畅的Python(第2版)
迭代器、生成器和经典协程
487
>>> g = (n for n in [0, 0.0, 7, 8])
>>> any(g)
True
>>> next(g)
8
any
迭代
g
,直到
g
产出
7
。此时,
any
停止,返回
True
因此,下一个值是
8
还有一个内置函数也接受一个可迭代对象,返回相关结果,即
sorted
函数。
reversed
是生
成器函数,而
sorted
不同,它构建并返回一个新列表。毕竟,要读取输入的可迭代对象中
的每一项才能排序,而且排序的对象是列表,因此
sorted
操作完成后返回排序后的列表。
我在这里提到
sorted
函数,是因为它可以处理任意的可迭代对象。
当然,
sorted
函数和归约函数只能处理最终会停止的可迭代对象。否则,这些函数一直收
集项,永远无法返回结果。
如果你坚持读到了这里,那么你已经读完了本章最重要和最有用的内容。余
下几节讨论的是生成器的高级功能,例如
yield from
结构和经典协程,大部
分人平时见不着也用不到。
另外,还有几节讨论可迭代对象、迭代器和经典协程的类型提示。
yield from
句法提供了一种组合生成器的新方式,接下来的
17.11
节会说明。
17.11
 
yield from
从子生成器中产出
Python 3.3
新增的
yield from
表达式句法可把一个生成器的工作委托给一个子生成器。
引入
yield from
之前,如果一个生成器根据另一个生成器生成的值产出值,则需要使用
for
循环。
>>> def sub_gen():
... yield ...
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高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
Python贝叶斯分析(第2版)

Python贝叶斯分析(第2版)

Posts & Telecom Press, Osvaldo Martin
高效能PYTHON程式設計

高效能PYTHON程式設計

Micha Gorelick, Ian Ozsvald

Publisher Resources

ISBN: 9787115612366