Python列表:元素的修改添加删除和排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python列表:元素的修改添加删除和排序相关的知识,希望对你有一定的参考价值。
本文参考自《Python编程:从入门到实践》,作者:Eric Matthes,译者:袁国忠
操作 | 语法 | 举例 | 结果 |
修改元素 |
motocycles = [‘honda‘, ‘yamaha‘, ‘suzuki‘] print (motocycles)
motocycles[0] = ‘ducati‘ print (motocycles) |
[‘honda‘, ‘yamaha‘, ‘suzuki‘]
[‘ducati‘, ‘yamaha‘, ‘suzuki‘] |
|
添加元素
|
在列表末尾添加元素:append() |
motocycles = [‘honda‘, ‘yamaha‘, ‘suzuki‘] print (motocycles)
motocycles.append(‘ducati‘) print (motocycles)
|
[‘honda‘, ‘yamaha‘, ‘suzuki‘]
[‘honda‘, ‘yamaha‘, ‘suzuki‘, ‘ducati‘] |
在列表中插入元素:insert() |
motocycles = [‘honda‘, ‘yamaha‘, ‘suzuki‘] print (motocycles)
motocycels.insert(0, ‘ducati‘) print (motocycles)
|
[‘honda‘, ‘yamaha‘, ‘suzuki‘]
[‘ducati‘, ‘honda‘, ‘yamaha‘, ‘suzuki‘] |
|
删除元素
|
根据索引删除:del,无法继续使用 |
motocycles = [‘honda‘, ‘yamaha‘, ‘suzuki‘] print (motocycles)
del motocycles[1] print (motocycles)
|
[‘honda‘, ‘yamaha‘, ‘suzuki‘]
[‘honda‘, ‘suzuki‘] |
删除末尾的元素:pop(),可以继续使用 也可以根据索引删除,如motocycles.pop(0) |
motocycles = [‘honda‘, ‘yamaha‘, ‘suzuki‘] print (motocycles)
popped_motocycle = motocycles.pop() print (motocycles) print (popped_motocycle)
|
[‘honda‘, ‘yamaha‘, ‘suzuki‘]
[‘honda‘, ‘yamaha‘]
suzuki
|
|
不知道索引时,根据值删除元素:remove(),可以继续使用
|
motocycles = [‘honda‘, ‘yamaha‘, ‘suzuki‘, ‘ducati‘] print (motocycles)
too_expensive = ‘ducati‘ motocycles.remove(too_expensive) print (motocycles) print (too_expensive) |
[‘honda‘, ‘yamaha‘, ‘suzuki‘, ‘ducati‘]
[‘honda‘, ‘yamaha‘, ‘suzuki‘]
ducati
|
|
元素排序 |
永久性排序:sort()
反方向排序:sort(reverse = True) |
cars = [‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘] print (cars)
cars.sort() print (cars)
cars = [‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘] cars.sort(reverse = True) print (cars) |
[‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘]
[‘audi‘, ‘bmw‘, ‘subaru‘, ‘toyota‘]
[‘toyota‘, ‘subaru‘, ‘bmw‘, ‘audi‘] |
临时性排序:sorted()
反方向排序:sorted(reverse = True) |
cars = [‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘] print (cars) print (sorted(cars)) print (cars) |
[‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘]
[‘audi‘, ‘bmw‘, ‘subaru‘, ‘toyota‘]
[‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘]
|
|
永久性反转列表元素的排列顺序:reverse() |
cars = [‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘] print (cars)
cars.reverse() print (cars)
cars.reverse() print (cars) |
[‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘]
[‘subaru‘, ‘toyota‘, ‘audi‘, ‘bmw‘]
[‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘] |
以上是关于Python列表:元素的修改添加删除和排序的主要内容,如果未能解决你的问题,请参考以下文章