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]

转载于:https://www.cnblogs.com/my_captain/p/7643244.html

你可能感兴趣的:(Python列表:元素的修改、添加、删除和排序)