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‘]
原文地址:https://www.cnblogs.com/yuxinjack/p/9842884.html
时间: 2024-10-25 01:27:31