四、列表简介-a

 

 

3.2.3   从列表中删除元素

   1.使用del语句删除元素

   如果知道要删除的元素在列表中的位置,可使用del语句。

1 motorcycles = ['honda','yamaha','suzuki']
2 print(motorcycles)
3 
4 del motorcycles[0]
5 print(motorcycles)

   4处的代码使用del删除了列表motorcycles中的第一个元素-----‘honda’

   使用del可删除任何位置处的列表元素,条件是知道其索引。

   演示删除前列表中的第二个元素-----‘yamaha’:

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)

del motorcycles[1]
print(motorcycles)

将第二款摩托车从列表中删除:

   在这两个示例中,使用del语句将值从列表中删除后,你就无法再访问它了。

 2.使用方法pop()删除元素

    方法pop()可删除列表末尾的元素,并让你能够接着使用它。术语弹出(pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。

    下面从列表motorcycles中弹出一款摩托车:

1 motorcycles = ['honda','yamaha','suzuki']
2 print(motorcycles)
3 
4 popped_motorcycle = motorcycles.pop()
5 print(motorcycles)
6 print(popped_motorcycle)

       我们首先定义并打印了列表motorcycles(见1)。接下来,我们从这个列表中弹出一个值,并将其存储到变量popped_motorcycle中(见4)。然后我们打印这个列表,以核实从其中删除了一个值(见5)。最后我们打印弹出的值,以证明我们依然能够访问被删除的值(见6)。

      输出表明,列表末尾的值‘suzuki’已删除,它现在存储在变量poped_motorcycle中:

       方法pop()是怎么起作用的呢?假设列表中的摩托车是按购买时间存储的,就可使用方法pop()打印一条消息,指出最后购买的是哪款摩托车:

 

motorcycles = ['honda','yamaha','suzuki']

last_owned = motorcycles.pop()
print("The last motorcycles I owned was a "+last_owned.title()+".")

    输出是一个简单的句子,指出了最新购买的是哪款摩托车:

 

 

3.弹出列表中任何位置处的元素

    实际上,可以使用pop()来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。

 

1 motorcycles = ['honda','yamaha','suzuki']
2 
3 first_owned = motorcycles.pop(0)
4 print("The first motorcycles I owned was a "+first_owned.title()+".")

   首先,我们弹出了列表中的第一款摩托车(见3),然后打印了一条有关这辆摩托车的消息(见4)。输出是一个简单的句子,描述了我购买的第一辆摩托车:

 

     别忘了,每当你使用pop()时,被弹出的元素就不再在列表中了。

      如果你不确定该使用del语句还是pop()方法,下面是一个简单的判断标准:如果你要从列表中删除一个元素后,且不再以任何方式使用它,就是用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop()。

      4.根据值删除元素

       有时候,你不知道要从列表中删除的值所处的位置。如果你只知道要删除的元素的值,可使用方法remove()。

       例如,假设我们要从列表motorcycles中删除值‘ducati’。

1 motorcycles = ['honda','yamaha','suzuki','ducati']
2 print(motorcycles)
3 
4 motorcycles.remove('ducati')
5 print(motorcycles)

    4处的代码让Python确定‘ducati’出现在列表的什么地方,并将钙元素删除:

    使用remove()从列表中删除元素时,也可接着使用它的值。下面删除值‘ducati’,并打印一条消息,指出要将其从列表中删除的原因:

1 motorcycles = ['honda','yamaha','suzuki','ducati']
2 print(motorcycles)
3 
4 too_expensive = 'ducati'
5 motorcycles.remove(too_expensive)
6 print(motorcycles)
7 print("\nA "+too_expensive.title()+" is too expensive for me.")

     在1处定义列表后,我们将值‘ducati’存储在变量too_expensive中(见4)。接下来,我们使用这个变量来告诉Python将哪个值从列表中删除(见5)。最后,值‘ducati’已经从列表中删除,但它还存储在变量too_expensive中(见7),让我们能够打印一条消息,指出将‘ducati’从列表motorcycles中删除的原因:

    注意:方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。

posted @ 2018-06-16 11:50  淺飲時光  阅读(107)  评论(0编辑  收藏  举报