3.2 修改添加和删除元素
Posted yuxinjack
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3.2 修改添加和删除元素相关的知识,希望对你有一定的参考价值。
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 修改添加和删除元素的主要内容,如果未能解决你的问题,请参考以下文章