码迷,mamicode.com
首页 > 编程语言 > 详细

Python:在列表中修改、添加和删除元素

时间:2020-05-03 23:11:04      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:除了   rem   结果   删除   was   tle   运行   它的   指定   

一、修改

代码示例

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

motorcycles[0] = ducati 
print(motorcycles)
运行结果

[honda, yamaha, suzuki] 
[ducati, yamaha, suzuki]

二、添加

  (一)使用append()添加在末尾

代码示例

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

motorcycles.append(ducati) 
print(motorcycles) 
方法append()将元素ducati添加到了列表末尾,而不影响列表中的其他所有元素:

[honda, yamaha, suzuki] 
[honda, yamaha, suzuki, ducati]

  (二)使用insert()在列表任意位置插入元素(需要指定新元素的索引和值)

代码示例

motorcycles = [honda, yamaha, suzuki] 
motorcycles.insert(0, ducati) 
print(motorcycles)
运行结果

[ducati, honda, yamaha, suzuki]

三、删除

  (一)使用del语句删除元素(知道要删除的元素在列表中的位置)

代码示例

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

del motorcycles[0] 
print(motorcycles)
运行结果

[honda, yamaha, suzuki] 
[yamaha, suzuki]

  (二)使用方法pop()删除元素(要将元素从列表中删除,并接着使用它的值,可以使用pop()来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。)

代码示例①

motorcycles = [honda, yamaha, suzuki] 
print(motorcycles) 
popped_motorcycle = motorcycles.pop() 
print(motorcycles) 
print(popped_motorcycle)
运行结果①(.pop()删除了列表中的末尾元素)

[honda, yamaha, suzuki] 
[honda, yamaha] 
suzuki
代码示例②

motorcycles = [honda, yamaha, suzuki] 
first_owned = motorcycles.pop(0) 
print(The first motorcycle I owned was a  + first_owned.title() + .)
运行结果②

The first motorcycle I owned was a Honda.

  (三)根据值删除元素(只知道要删除的元素的值,不知道要从列表中删除的值所处的位置。可使用方法remove(),可接着使用它的值)

代码示例①

motorcycles = [honda, yamaha, suzuki, ducati] 
print(motorcycles) 
motorcycles.remove(ducati) 
print(motorcycles)
运行结果①

[honda, yamaha, suzuki, ducati] 
[honda, yamaha, suzuki]
代码示例②

motorcycles = [honda, yamaha, suzuki, ducati]
print(motorcycles) 
too_expensive = ducati 
motorcycles.remove(too_expensive) 
print(motorcycles) 
print("\nA " + too_expensive.title() + " is too expensive for me.")
运行结果②

[honda, yamaha, suzuki, ducati] 
[honda, yamaha, suzuki] 
A Ducati is too expensive for me.

 

Python:在列表中修改、添加和删除元素

标签:除了   rem   结果   删除   was   tle   运行   它的   指定   

原文地址:https://www.cnblogs.com/pyme/p/12824440.html

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