多平台统一管理软件接口,如何实现多平台统一管理软件接口
292
2022-08-26
Python列表:元素的修改、添加、删除和排序(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'] | |
有返回值,不会改变原值
临时性反转列表的排列顺序:[: : -1] | num = [1, 2, 3, 4]
num_new = num[::-1] print(num_new)
print(num) |
[4, 3, 2, 1]
[1, 2, 3, 4] | |
合并列表 | +或extend | A = [1, 2, 3, 4] B = [5, 6, 7, 8] A = A + B 或 A.extend(B)
print(A) |
[1, 2, 3, 4, 5, 6, 7, 8] |
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~