导航菜单

  • 1.Python介绍
  • 2.Python解释器
  • 3.安装Python
  • 4.VSCode开发Python
  • 5.print
  • 6.进制
  • 7.编码
  • 8.Unicode2UTF8
  • 9.整数类型
  • 10.字符串类型
  • 11.布尔类型
  • 12.变量与内存
  • 13.浮点类型
  • 14.注释
  • 15.if条件
  • 16.while循环
  • 17.运算符
  • 18.输入
  • 19.列表
  • 20.元组
  • 21.集合
  • 22.字典
  • 23.for循环
  • 19.1 列表是什么?
  • 19.2 创建与访问
  • 19.3 增删元素
  • 19.4 常用操作
  • 19.5 遍历
  • 19.6 列表推导式
  • 19.7 复制与嵌套
  • 19.8 项目开发要点

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)        # 需要索引时用 enumerate

19.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 项目开发要点 #

  1. 接口数据:response.json() 常常是 list[dict],用 for item in data 处理
  2. append vs extend:合并列表用 extend;追加单个对象用 append
  3. 排序:展示用 sorted() 保留原列表;确定要改原列表用 .sort()
  4. 不要用列表当下标字典:需要按 id 查找时用 dict,不要 list.index 反复查
  5. 共享引用:赋值 b = a 共享同一列表;要副本用 .copy() 或 list(a)
  6. 空列表判断:if not items: 即可
← 上一节 18.输入 下一节 20.元组 →

访问验证

请输入访问令牌

Token不正确,请重新输入