Skip to Content
Python实用技能学习指南
book

Python实用技能学习指南

by Posts & Telecom Press, Robert Smallshire, Austin Bingham
February 2024
Intermediate to advanced
316 pages
3h 47m
Chinese
Packt Publishing
Content preview from Python实用技能学习指南

第7章 推导、可迭代与生成器

对象序列的抽象概念在编程中无处不在。它可以用于塑造大不相同的对象,诸如简单字符串、复杂对象的列表和无限长的传感输出流。Python包含了一些非常强大和优雅的处理序列的工具,你可能不会对此感到惊讶。事实上,对于很多人来说,Python支持创建和操作序列的功能是选择它之一。

在本章中,我们将介绍Python提供的用于处理序列的3个关键工具:推导(comprehension)、可迭代(iterable)与生成器(generator)。推导包括以声明方式创建各种类型的序列的专用语法。可迭代迭代协议(iteration protocol)构成了Python中的序列与迭代的核心抽象和API。你可以使用它们定义新的序列类型,并对迭代进行细粒度的控制。最后,我们可以使用生成器命令式地定义惰性序列,在很多情况下,这是一项惊人的强大技术。

让我们马上开始学习推导。

Python中的推导是一项简洁的语法,它可以用于以声明式或者函数式的方式描述的列表、集合或字典。这种语法易读且富有表达力,这意味着推导可以非常有效地向读者传达意图。有一些推导看起来几乎像是自然语言,这使得它们自身就是很好的文档。

如上所述,列表推导是一种创建列表的简单方法。它是一个使用了简明语法的表达式,该表达式描述了如何定义列表元素

演示推导要比解释它们容易得多,因此需要开启一个Python REPL。首先,通过拆分字符串来创建一个单词列表:

>>> words = "If there is hope it lies in the proles".split() >>> words ['If', 'there', 'is', 'hope', 'it', 'lies', ...
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

人工智能技术与大数据

人工智能技术与大数据

Posts & Telecom Press, Anand Deshpande, Manish Kumar
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835889626