Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
80
7
7.2
列表
列表非常适合根据顺序定位元素,尤其是当元素的顺序或内容会发生改变时。与字符串不
同,列表是可变的。可以就地修改列表,向其中添加新元素,删除或替换已有元素。在列
表中,同样的值可以多次出现。
7.2.1
使用
[]
创建列表
列表可以包含
0
个或多个元素,元素之间用逗号分隔,置于一对方括号内:
>>> empty_list = [ ]
>>> weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
>>> big_birds = ['emu', 'ostrich', 'cassowary']
>>> first_names = ['Graham', 'John', 'Terry', 'Terry', 'Michael']
>>> leap_years = [2000, 2004, 2008]
>>> randomness = ['Punxsatawney", {"groundhog": "Phil"}, "Feb. 2"}
first_names
列表展示了值是可以重复的。
如果你想记录不重复的值,且不在乎顺序关系,则集合可能比列表更适合。
在上面的例子中,
big_birds
就可以作为集合。第
8
章会探讨集合。
7.2.2
使用
list()
创建或转换列表
也可以使用
list()
函数生成一个空列表:
>>> another_empty_list = list()
>>> another_empty_list ...
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.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223