19.1 列表是什么? #
列表是有序、可变的集合,可存任意类型,项目里极常见:用户列表、订单 ID、接口返回的 JSON 数组等。
users = ["alice", "bob"]
print(users)
mixed = [1, "ok", True]
print(mixed)
empty = []
print(empty)19.2 创建与访问 #
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # apple
print(fruits[-1]) # orange(最后一个)
print(fruits[1:3]) # ['banana', 'orange'](切片,不含索引 3)
fruits[1] = "blueberry" # 修改元素19.3 增删元素 #
| 方法 | 作用 |
|---|---|
append(x) |
末尾加一个元素 |
extend(iterable) |
末尾合并多个元素 |
insert(i, x) |
在索引 i 插入 |
remove(x) |
删除第一个值为 x 的元素 |
pop() / pop(i) |
删除并返回末尾或指定索引 |
clear() |
清空 |
items = [1, 2]
items.append(3) # [1, 2, 3]
print(items)
items.extend([4, 5]) # [1, 2, 3, 4, 5]
print(items)
items.append([6, 7]) # [..., [6, 7]] 整个子列表作为一个元素
print(items)
items = [1, 2]
items.extend([6, 7]) # [1, 2, 6, 7] 逐个并入
print(items)
items.remove(2)
print(items)
last = items.pop() # 弹出最后一个
print(last)
print(items)19.4 常用操作 #
tags = ["python", "web"]
print(len(tags)) # 2
print("web" in tags) # True
print(", ".join(tags)) # python, web(字符串拼接)
nums = [3, 1, 4, 1, 5]
nums.sort() # 原地排序:[1, 1, 3, 4, 5]
print(nums)
sorted_nums = sorted(nums) # 返回新列表,不改变原列表(需要保留原序时用)
print(sorted_nums)19.5 遍历 #
orders = ["A001", "A002", "A003"]
for order_id in orders:
print(order_id)
for i, order_id in enumerate(orders):
print(i, order_id) # 需要索引时用 enumerate19.6 列表推导式 #
用一行从已有序列生成新列表,项目里很常用:
nums = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in nums]
evens = [x for x in nums if x % 2 == 0]
names = ["Alice", "Bob"]
lower_names = [n.lower() for n in names]复杂逻辑仍用普通 for,可读性优先。
19.7 复制与嵌套 #
a = [1, 2, 3]
b = a.copy() # 或 b = a[:],浅拷贝
b.append(4) # a 不变
# 嵌套列表修改内层会影响原列表,完全独立副本用 copy.deepcopy()(19.8 项目开发要点 #
- 接口数据:
response.json()常常是list[dict],用for item in data处理 appendvsextend:合并列表用extend;追加单个对象用append- 排序:展示用
sorted()保留原列表;确定要改原列表用.sort() - 不要用列表当下标字典:需要按 id 查找时用
dict,不要list.index反复查 - 共享引用:赋值
b = a共享同一列表;要副本用.copy()或list(a) - 空列表判断:
if not items:即可