码迷,mamicode.com
首页 > 其他好文 > 详细

3.2 修改、添加和删除元素

时间:2018-10-24 15:30:55      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:int   nbsp   end   根据   first   使用方法   bsp   2.3   添加   

3.2.1 修改列表元素

motorcycles = [honda, yamaha, suzuki]
print(motorcycles)
motorcycles[0] = ducati
print(motorcycles)
[honda, yamaha, suzuki]
[ducati, yamaha, suzuki]

3.2.2在列表中添加元素

在列表末尾添加元素

motorcycles = [honda, yamaha, suzuki]
print(motorcycles)
motorcycles.append(ducati)
print(motorcycles)
[honda, yamaha, suzuki]
[honda, yamaha, suzuki, ducati]

在列表中插入元素

motorcycles = [honda, yamaha, suzuki]
print(motorcycles)
motorcycles.insert(0,ducati)
print(motorcycles)
[honda, yamaha, suzuki]
[ducati, honda, yamaha, suzuki]

3.2.3 从列表中删除元素

1.使用del语句删除元素

motorcycles = [honda, yamaha, suzuki]
print(motorcycles)
del motorcycles[0]
print(motorcycles)
[honda, yamaha, suzuki]
[yamaha, suzuki]

 

motorcycles = [honda, yamaha, suzuki]
print(motorcycles)
del motorcycles[1]
print(motorcycles)
[honda, yamaha, suzuki]
[honda, suzuki]

使用方法pop()删除元素

motorcycles = [honda, yamaha, suzuki]
print(motorcycles)
popped_motorcycles = motorcycles.pop()
print(motorcycles)
print(popped_motorcycles)
[honda, yamaha, suzuki]
[honda, yamaha]
suzuki

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

motorcycles = [honda, yamaha, suzuki]
print(motorcycles)
popped_motorcycles = motorcycles.pop(0)
print("The first motorcycle I owned was a " + popped_motorcycles.title() + ".")
[honda, yamaha, suzuki]
The first motorcycle I owned was a Honda.

根据值删除元素

motorcycles = [honda, yamaha, suzuki,ducati]
print(motorcycles)
motorcycles.remove(ducati)
print(motorcycles)
[honda, yamaha, suzuki, ducati]
[honda, yamaha, suzuki]

 

3.2 修改、添加和删除元素

标签:int   nbsp   end   根据   first   使用方法   bsp   2.3   添加   

原文地址:https://www.cnblogs.com/yuxinjack/p/9842884.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!