本章和下一章,将学习列表是什么以及如何使用列表元素。列表让你能够在一个地方存储成组的信息。
认识列表 列表由一系列按特定顺序排列的元素组成。鉴于列表通常包含多个元素,给列表指定一个表示复数的名称是个不错的主意。
Python中,用 [ ] 来表示列表,用逗号分隔其中的元素。示例:
1 2 bicycles = ['trek' , 'cannondale' , 'redline' , 'specialized' ]print (bicycles)
1.访问列表元素 1 2 3 4 5 bicycles = ['trek' , 'cannondale' , 'redline' , 'specialized' ]print (bicycles[0 ]) print (bicycles[-1 ])
2.修改、添加和删除元素 修改元素:
1 2 3 4 5 motorcycles = ['honda' , 'yamaha' , 'suzuki' ]print (motorcycles) motorcycles[0 ] = 'ducati' print (motorcycles)
添加元素:
1 2 3 4 5 6 motorcycles.append('honda' )print (motorcycles) motorcycles.insert(0 ,'ducatipro' )print (motorcycles)
删除元素:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 del motorcycles[0 ]print (motorcycles) poped_motorcycle = motorcycles.pop()print (motorcycles) print (poped_motorcycle) poped_motorcycle = motorcycles.pop(0 )print (motorcycles) print (poped_motorcycle) too_expensive = 'yamaha' motorcycles.remove(too_expensive)print (motorcycles) print (too_expensive)
3.组织列表 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 cars = ['bmw' , 'audi' , 'toyota' , 'subaru' ] cars.sort()print (cars) cars.sort(reverse=True )print (cars) print (cars) print (sorted (cars)) cars.reverse()print (cars) print (len (cars))