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实用技能学习指南

第5章 探究内置集合类型

我们已经遇到了一些内置的集合(collection):

  • str——不可变的Unicode码位字符串序列;
  • list——可变的对象序列;
  • dict——可变的字典,它将不可变的键映射到可变的对象。

我们只是对这些集合类型的用法浅尝辄止,所以,在本章中,我们将深入探讨它们的功能。同时,本章还将介绍3种新的内置集合类型:

  • tuple——不可变的对象序列;
  • range——对于整数的等差序列;
  • set——包含唯一、可变对象的可变集。

本章不会再进一步讲解bytes类型。我们已经讨论了它与str的本质区别,学过的大多数关于str的知识也适用于字节。

这里不会详尽地列出所有的Python集合类型,但是对于绝大多数你将在外面遇到的或者可能自己编写的Python 3程序来说,这几个集合类型是完全够用的。

在本章中,我们将按照上面提到的顺序来介绍这些集合类型,最后将介绍协议(protocol),是协议将集合统一到一起,从而我们能够以一致和可预测的方式使用它们。

在Python中,元组(tuple)是可以包含任意对象的不可变序列。一旦创建了元组,就不能替换或删除其中的对象,并且不能向它添加新的元素。

元组与列表具有相似的字面量语法,只是元组是由圆括号包裹而不是方括号。以下是一个包含字符串、浮点数和整数的元组字面量:

>>> t = ("Norway", 4.953, 3)
>>> t
('Norway', 4.953, 3)

可以在方括号里使用从0开始的索引来访问元组中的元素:

>>> t[0]
'Norway'
>>> t[2]
3

可以使用内置的

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