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版)
元组和列表
85
7.2.12
使用
del
按偏移删除列表项
校对员刚刚告诉我们,
Gummo
确实是
Marx
兄弟中的一员,但
Karl
不是,早先将其列入
名单的人实在是太失礼了。我们得修正一下:
>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Karl']
>>> marxes[-1]
'Karl'
>>> del marxes[-1]
>>> marxes
['Groucho', 'Chico', 'Harpo', 'Gummo']
当列表中某个位置上的内容被删除后,位于其后的列表项会向前移动,补上空出的位置,
并且列表长度减
1
。如果从更新后的
marxes
列表中删除
'Chico'
,则结果如下。
>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Gummo']
>>> del marxes[1]
>>> marxes
['Groucho', 'Harpo', 'Gummo']
del
Python
语句
,并非列表方法,不能写作
marxes[-2].del()
del
有些
像赋值(
=
)的反操作:它会解除名称与
Python
对象之间的关联,如果该对
象再无其他名称引用,则所占用的内存也被会释放。
7.2.13
使用
remove()
按值删除列表项
如果不确定或不关心列表项的位置,可以使用
remove()
按值删除。再见了,
Groucho
>>> marxes = ['Groucho', 'Chico', 'Harpo'] ...
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