# Python 列表
## 简介
在进行数据科学时,我们需要有效组织数据。Python 提供了多种数据结构,其中列表(list)是最常用的基础数据结构之一。本教程将详细介绍 Python 列表的使用方法。
## 动机
在「Petal to the Metal」花朵分类竞赛中,我们需要根据图像识别花卉种类。假设我们有以下花卉名称数据:
**字符串存储方式**
```python
flowers = "pink primrose,hard-leaved pocket orchid,canterbury bells,sweet pea,english marigold,tiger lily,moon orchid,bird of paradise,monkshood,globe thistle"
这种字符串形式难以直接操作,例如:
- 获取特定位置的元素
- 统计元素数量
- 动态增删元素
列表存储方式
flowers_list = [
"pink primrose",
"hard-leaved pocket orchid",
"canterbury bells",
"sweet pea",
"english marigold",
"tiger lily",
"moon orchid",
"bird of paradise",
"monkshood",
"globe thistle"
]
列表显著提升了数据操作的便利性。
列表操作
长度查询
使用 len()
获取元素数量:
print(len(flowers_list)) # 输出:10
元素访问(索引)
Python 使用零基索引:
print("第一个元素:", flowers_list[0]) # pink primrose
print("第二个元素:", flowers_list[1]) # hard-leaved pocket orchid
print("最后一个元素:", flowers_list[9]) # globe thistle
切片操作
提取子列表:
print("前三个元素:", flowers_list[:3])
# 输出:['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells']
print("最后两个元素:", flowers_list[-2:])
# 输出:['monkshood', 'globe thistle']
元素删除
使用 .remove()
方法:
flowers_list.remove("globe thistle")
print(flowers_list) # 最后一个元素被删除
元素添加
使用 .append()
方法:
flowers_list.append("snapdragon")
print(flowers_list) # 列表末尾新增元素
数值列表操作
列表支持存储任意数据类型,例如记录图书销量:
hardcover_sales = [139, 128, 172, 139, 191, 168, 170]
基础统计
print("列表长度:", len(hardcover_sales)) # 7
print("索引2的值:", hardcover_sales[2]) # 172
print("最小值:", min(hardcover_sales)) # 128
print("最大值:", max(hardcover_sales)) # 191
print("周销售总量:", sum(hardcover_sales)) # 1107
切片计算
计算前五天的平均销量:
average_first_five = sum(hardcover_sales[:5])/5
print("前五天平均销量:", average_first_five) # 153.8
关键特性总结
特性 | 说明 | 示例 |
---|---|---|
动态大小 | 可自由增删元素 | .append() , .remove() |
异质数据类型 | 支持混合存储不同类型 | [1, "apple", True] |
索引访问 | O(1) 时间复杂度访问 | list[0] |
内置计算方法 | 快速统计操作 | sum() , max() |
提示:列表是可变对象,所有修改操作会直接改变原列表。使用切片时会产生新列表。