Python-列表与序列
·
一、什么是序列?
序列(Sequence) = 有序、可按索引访问的数据类型。
Python 中常见的序列:
| 类型 | 可变? | 语法 |
|---|---|---|
| 字符串 str | ❌ | 'hello' |
| 列表 list | ✅ | [1, 2, 3] |
| 元组 tuple | ❌ | (1, 2, 3) |
序列通用操作(str、list、tuple 都支持):
s = "Python"
lst = [1, 2, 3, 4, 5]
# 索引
print(s[0], lst[0]) # P 1
# 切片
print(s[0:3], lst[1:4]) # Pyt [2, 3, 4]
# 拼接 +
print([1, 2] + [3, 4]) # [1, 2, 3, 4]
# 重复 *
print([0] * 5) # [0, 0, 0, 0, 0]
# 成员检测 in
print(2 in lst) # True
# 长度 len
print(len(lst)) # 5
# 最大最小
print(max(lst), min(lst))
二、列表 List 详解
2.1 列表的特点
- 可变:创建后可以修改、添加、删除元素
- 有序:每个元素有固定位置(索引)
- 元素类型可以不同:
[1, "hello", 3.14, True]
2.2 创建列表
lst1 = [1, 2, 3]
lst2 = list("abc") # ['a', 'b', 'c']
lst3 = list(range(5)) # [0, 1, 2, 3, 4]
lst4 = [] # 空列表
lst5 = [1, "hello", 3.14] # 混合类型
nested = [[1, 2], [3, 4]] # 嵌套列表
2.3 访问元素
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # apple(第一个)
print(fruits[-1]) # date(最后一个)
print(fruits[1:3]) # ['banana', 'cherry'](切片)
2.4 修改元素
fruits = ["apple", "banana", "cherry"]
# 按索引修改
fruits[0] = "apricot"
# 切片赋值(可改变长度!)
fruits[1:2] = ["blueberry", "blackberry"]
print(fruits) # ['apricot', 'blueberry', 'blackberry', 'cherry']
2.5 添加元素
fruits = ["apple", "banana"]
fruits.append("cherry") # 末尾添加单个
fruits.insert(1, "blueberry") # 指定位置插入
fruits.extend(["date", "elderberry"]) # 末尾批量添加
print(fruits)
| 方法 | 作用 |
|---|---|
append(x) |
末尾添加一个元素(即使 x 是列表,也作为整体添加) |
insert(i, x) |
在索引 i 处插入 x |
extend(iterable) |
末尾逐个添加 iterable 中的元素 |
a = [1, 2]
a.append([3, 4]) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4]) # [1, 2, 3, 4]
2.6 删除元素
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana") # 删除第一个匹配的值
del fruits[0] # 按索引删除
popped = fruits.pop() # 弹出末尾元素
popped = fruits.pop(0) # 弹出指定位置
fruits.clear() # 清空列表
2.7 查找与统计
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print(nums.index(4)) # 2(第一次出现的索引)
print(nums.count(1)) # 2(出现次数)
print(5 in nums) # True
2.8 排序与反转
nums = [3, 1, 4, 1, 5]
nums.sort() # 原地升序,nums 本身被改变
nums.sort(reverse=True) # 原地降序
original = [3, 1, 4]
sorted_list = sorted(original) # 返回新列表,original 不变
nums.reverse() # 原地反转
sort() vs sorted():
| sort() | sorted() | |
|---|---|---|
| 调用方式 | 列表方法 lst.sort() |
内置函数 sorted(lst) |
| 是否改变原列表 | ✅ 改变 | ❌ 返回新列表 |
2.9 遍历列表
fruits = ["apple", "banana", "cherry"]
# 方式1:直接遍历
for fruit in fruits:
print(fruit)
# 方式2:带索引
for i, fruit in enumerate(fruits):
print(i, fruit)
# 0 apple
# 1 banana
# 2 cherry
2.10 列表推导式(重点!)
简洁地创建列表:
# 基本形式
squares = [x ** 2 for x in range(10)]
# 带条件
evens = [x for x in range(20) if x % 2 == 0]
# 多重循环
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
# 从现有列表转换
words = ["hello", "world", "python"]
upper_words = [w.upper() for w in words]
lengths = [len(w) for w in words]
2.11 zip() 函数
把多个序列"拉链"合并:
names = ["张三", "李四", "王五"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
pairs = list(zip(names, scores))
# [('张三', 85), ('李四', 92), ('王五', 78)]
三、列表 vs 字符串
| 特性 | str | list |
|---|---|---|
| 可变性 | 不可变 | 可变 |
| 元素类型 | 只能是字符 | 任意类型 |
| 拼接 | + |
+ |
| 重复 | * |
* |
四、重点易错点
- append vs extend:append 添加整个对象,extend 逐个添加
- remove 找不到会 ValueError
- 切片赋值可改变列表长度
- 列表是引用类型:
b = a两个变量指向同一列表
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4] a 也变了!
五、练习题
基础题
1. 创建 1~20 的列表,用切片取出所有偶数。
2. 列表 [3, 1, 4, 1, 5, 9, 2, 6] 去重并升序排列。
3. 用列表推导式生成 1~100 中能被 3 整除的数。
4. 有两个列表 names=["张三","李四"] 和 scores=[85,92],用 zip 合并输出。
5. 实现列表扁平化:[[1,2],[3,4],[5]] → [1,2,3,4,5]。
进阶题
6. 找出列表第二大元素(不允许 sort 整个列表)。
7. 旋转列表:将 [1,2,3,4,5] 左旋转 2 位得 [3,4,5,1,2]。
参考答案
点击展开参考答案
# 1.
nums = list(range(1, 21))
evens = nums[1::2] # 或 [x for x in nums if x % 2 == 0]
# 2.
lst = [3, 1, 4, 1, 5, 9, 2, 6]
result = sorted(set(lst))
# 3.
div3 = [x for x in range(1, 101) if x % 3 == 0]
# 4.
for name, score in zip(names, scores):
print(f"{name}: {score}")
# 5.
nested = [[1, 2], [3, 4], [5]]
flat = [item for sub in nested for item in (sub if isinstance(sub, list) else [sub])]
# 6.
def second_max(lst):
m1 = m2 = float('-inf')
for x in lst:
if x > m1: m2, m1 = m1, x
elif x > m2: m2 = x
return m2
# 7.
lst = [1, 2, 3, 4, 5]
k = 2
rotated = lst[k:] + lst[:k]
更多推荐
所有评论(0)