Python编程实战 · 基础入门篇 | 列表(list)

在 Python 中,列表(list) 是最常用、最灵活的数据结构之一。 它能存放多个数据,可以增删改查,还能嵌套其他列表,是编程中处理"集合类信息"的核心工具。

本章我们将系统学习列表的定义、操作方法、常用函数与实战应用。


一、什么是列表

列表(list)是一个 有序、可变 的元素集合。 它可以存储任意类型的数据,包括数字、字符串、布尔值、甚至其他列表。

示例:

python 复制代码
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", True, 3.14]
nested = [1, [2, 3], [4, 5]]

二、创建列表的方式

1. 使用方括号 []

python 复制代码
nums = [10, 20, 30, 40]

2. 使用内置函数 list()

python 复制代码
nums = list((10, 20, 30))

3. 创建空列表

python 复制代码
empty_list = []
# 或
empty_list = list()

三、访问列表元素

列表是有序的,可以通过 索引(index) 访问元素。

1. 正向索引(从 0 开始)

python 复制代码
fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # 输出 apple
print(fruits[2])  # 输出 cherry

2. 反向索引(从 -1 开始)

python 复制代码
print(fruits[-1])  # 输出 cherry
print(fruits[-2])  # 输出 banana

3. 切片(slice)

可以取出部分元素,形成新的列表:

python 复制代码
print(fruits[0:2])   # ['apple', 'banana']
print(fruits[1:])    # ['banana', 'cherry']
print(fruits[:2])    # ['apple', 'banana']

四、修改列表内容

1. 直接修改元素

python 复制代码
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits)

输出:

css 复制代码
['apple', 'orange', 'cherry']

2. 替换多个元素

python 复制代码
fruits[0:2] = ["pear", "melon"]
print(fruits)

输出:

css 复制代码
['pear', 'melon', 'cherry']

五、添加元素

1. append() --- 在列表末尾添加元素

python 复制代码
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)

输出:

css 复制代码
['apple', 'banana', 'cherry']

2. insert() --- 在指定位置插入元素

python 复制代码
fruits.insert(1, "orange")
print(fruits)

输出:

css 复制代码
['apple', 'orange', 'banana', 'cherry']

3. extend() --- 合并另一个列表

python 复制代码
fruits = ["apple", "banana"]
more = ["cherry", "peach"]
fruits.extend(more)
print(fruits)

输出:

css 复制代码
['apple', 'banana', 'cherry', 'peach']

六、删除元素

1. del 删除指定位置的元素

python 复制代码
fruits = ["apple", "banana", "cherry"]
del fruits[1]
print(fruits)

输出:

css 复制代码
['apple', 'cherry']

2. pop() --- 删除并返回元素(默认最后一个)

python 复制代码
fruits = ["apple", "banana", "cherry"]
item = fruits.pop()
print(item)
print(fruits)

输出:

css 复制代码
cherry
['apple', 'banana']

3. remove() --- 删除指定值的第一个匹配项

python 复制代码
fruits = ["apple", "banana", "apple", "cherry"]
fruits.remove("apple")
print(fruits)

输出:

css 复制代码
['banana', 'apple', 'cherry']

4. clear() --- 清空整个列表

python 复制代码
fruits.clear()
print(fruits)

输出:

css 复制代码
[]

七、遍历列表

示例:

python 复制代码
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

输出:

复制代码
apple
banana
cherry

八、判断与统计

1. 判断元素是否存在

python 复制代码
if "apple" in fruits:
    print("有苹果")

2. 统计元素数量

python 复制代码
count = fruits.count("apple")
print(count)

3. 获取列表长度

python 复制代码
print(len(fruits))

九、排序与反转

1. 升序排序

python 复制代码
nums = [3, 1, 4, 2]
nums.sort()
print(nums)

输出:

csharp 复制代码
[1, 2, 3, 4]

2. 降序排序

python 复制代码
nums.sort(reverse=True)
print(nums)

输出:

csharp 复制代码
[4, 3, 2, 1]

3. 临时排序(不改变原列表)

python 复制代码
nums = [3, 1, 4, 2]
print(sorted(nums))
print(nums)

输出:

csharp 复制代码
[1, 2, 3, 4]
[3, 1, 4, 2]

4. 反转列表

python 复制代码
nums.reverse()
print(nums)

输出:

csharp 复制代码
[2, 4, 1, 3]

十、列表的复制

1. 浅拷贝(copy)

python 复制代码
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a, b)

输出:

css 复制代码
[1, 2, 3] [1, 2, 3, 4]

2. 切片复制

python 复制代码
b = a[:]

✅ 注意:浅拷贝不会复制嵌套结构中的子列表。


十一、嵌套列表

列表中可以再包含列表,形成二维或多维结构。

python 复制代码
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(matrix[1][2])  # 输出6

十二、列表常用内置函数总结

函数 作用
len(list) 获取长度
max(list) 最大值
min(list) 最小值
sum(list) 求和(元素为数值时)
list.index(x) 获取元素索引
list.count(x) 统计出现次数
list.sort() 排序
list.reverse() 反转
list.copy() 浅拷贝

十三、实战案例:学生成绩分析

python 复制代码
scores = [85, 92, 78, 90, 88, 76, 95]

# 1. 平均分
avg = sum(scores) / len(scores)

# 2. 最高分与最低分
max_score = max(scores)
min_score = min(scores)

# 3. 排序
sorted_scores = sorted(scores, reverse=True)

print(f"平均分:{avg:.2f}")
print(f"最高分:{max_score}")
print(f"最低分:{min_score}")
print(f"从高到低排序:{sorted_scores}")

输出:

css 复制代码
平均分:86.29
最高分:95
最低分:76
从高到低排序:[95, 92, 90, 88, 85, 78, 76]

十四、小结

操作类别 方法或语法 示例
创建 []list() list(range(5))
访问 索引、切片 a[0]a[1:3]
修改 赋值 a[1] = 10
添加 append()extend()insert() a.append(6)
删除 pop()remove()del a.pop(0)
遍历 for for i in a:
排序 sort()sorted() a.sort()
统计 len()sum()count() len(a)

✅ 一句话总结

列表是 Python 最灵活的数据容器,几乎所有程序逻辑都能用它表示。


下一章,我们将学习 元组(tuple) , 了解一种不可变但更安全高效的数据结构。

相关推荐
码事漫谈12 小时前
从后端开发者到Agent工程师:一份系统性的学习指南
后端
一晌小贪欢12 小时前
【Python办公】处理 CSV和Excel 文件操作指南
开发语言·python·excel·excel操作·python办公·csv操作
码事漫谈12 小时前
后端开发如何将创新转化为专利?案例、流程与实操指南
后端
檀越剑指大厂13 小时前
【Python系列】fastapi和flask中的阻塞问题
python·flask·fastapi
小坏讲微服务13 小时前
SpringCloud零基础学全栈,实战企业级项目完整使用
后端·spring·spring cloud
humors22113 小时前
服务端开发案例(不定期更新)
java·数据库·后端·mysql·mybatis·excel
YoungHong199213 小时前
【Python进阶】告别繁琐Debug!Loguru一键输出异常日志与变量值
python·debug·异常处理·日志·loguru·log·logger
AiXed14 小时前
PC微信协议之nid算法
python·网络协议·算法·微信
小李哥哥15 小时前
基于数据的人工智能建模流程及源码示例
python
APIshop15 小时前
实战解析:苏宁易购 item_search 按关键字搜索商品API接口
开发语言·chrome·python