Python:在列表中修改添加和删除元素
Posted pyme
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python:在列表中修改添加和删除元素相关的知识,希望对你有一定的参考价值。
一、修改
代码示例 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(" A " + too_expensive.title() + " is too expensive for me.")
运行结果② [‘honda‘, ‘yamaha‘, ‘suzuki‘, ‘ducati‘] [‘honda‘, ‘yamaha‘, ‘suzuki‘] A Ducati is too expensive for me.
以上是关于Python:在列表中修改添加和删除元素的主要内容,如果未能解决你的问题,请参考以下文章