03. 弹出列表中任何位置处的元素
实际上,可以使用pop() 来删除列表中任意位置的元素,只需在圆括号中指定要删 除元素的索引即可。 motorcycles = ['honda', 'yamaha', 'suzuki'] ❶ first_owned = motorcycles.pop(0) ❷ print(f"The first motorcycle I owned was a {first_owned.title()}.") 首先弹出列表中的第一款摩托车(见❶),然后打印一条有关这辆摩托车的消息(见 ❷)。输出是一个简单的句子,描述了我购买的第一辆摩托车: The first motorcycle I owned was a Honda. 别忘了,每当你使用pop() 时,被弹出的元素就不再在列表中了。 如果你不确定该使用del 语句还是pop() 方法,下面是一个简单的判断标准:如果 你要从列表中删除一个元素,且不再以任何方式使用它,就使用del 语句;如果你 要在删除元素后还能继续使用它,就使用方法pop() 。
04. 根据值删除元素
有时候,你不知道要从列表中删除的值所处的位置。如果只知道要删除的元素的 值,可使用方法remove() 。 例如,假设要从列表motorcycles 中删除值'ducati' 。 motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] print(motorcycles) ❶ motorcycles.remove('ducati') print(motorcycles) ❶处的代码让Python确定'ducati' 出现在列表的什么地方,并将该元素删除: ['honda', 'yamaha', 'suzuki', 'ducati'] ['honda', 'yamaha', 'suzuki'] 使用remove() 从列表中删除元素时,也可接着使用它的值。下面删除 值'ducati' 并打印一条消息,指出要将其从列表中删除的原因:
❶ motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
❷ too_expensive = 'ducati'
❸ motorcycles.remove(too_expensive)
print(motorcycles)
❹ print(f"\nA {too_expensive.title()} is too expensive for me.")
定义列表(见❶)后,将值'ducati' 赋给变量too_expensive (见❷)。接下 来,使用这个变量来告诉Python将哪个值从列表中删除(见❸)。最后, 值'ducati' 已经从列表中删除,但可通过变量too_expensive 来访问它&#