一、列表是什么
- 列表由一系列按特定顺序排列的元素组成。
- 在Python中,用方括号([])表示列表,并用逗号分隔其中的元素。
- 访问列表元素:print(bicycles[0])。索引指定为-1,可以返回最后一个列表元素:print(bicycles[-1])
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
二、修改、添加和删除元素
- 在列表中修改元素:motorcycles[0] = ‘ducati’
- 在列表末尾添加元素:motorcycles.append(‘ducati’)
- 在列表中插入元素:motorcycles.insert(0,‘ducati’)
- 在列表中删除元素:
- del motorcycles[0]
- first_owned = motorcycles.pop(0)
- motorcycles.remove(‘ducati’)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
三、组织列表
- sort()对列表永久排序
- sorted()对列表临时排序
- reverse()倒着打印列表
- len()确定列表的长度
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
四、使用列表时避免索引错误
- Python试图向你提供位于索引3处的元素,但它搜索列表motorcycles时,却发现索引3处没有元素。
- 在Python中,第三个元素的索引为2,因为索引是从0开始的。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[3])
五、总结
在本章学习了:
- 列表是什么以及如何使用其中的元素
- 如何定义列表以及如何增删元素
- 如何对列表进行永久性排序,以及如何为展示列表而进行临时排序
- 如何确定列表的长度,以及在使用列表时如何避免索引错误