1. 列表是什么? #

users = ["alice", "bob"]
print(users)
mixed = [1, "ok", True]
print(mixed)
empty = []
print(empty)

2. 创建与访问 #

fruits = ["apple", "banana", "orange"]

print(fruits[0])      # apple
print(fruits[-1])     # orange(最后一个)
print(fruits[1:3])    # ['banana', 'orange'](切片,不含索引 3)

fruits[1] = "blueberry"   # 修改元素

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)

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)

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

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]

7. 复制与嵌套 #

a = [1, 2, 3]
b = a.copy()          # 或 b = a[:],浅拷贝
b.append(4)           # a 不变

nested = [[1, 2], [3, 4]]
shallow = nested.copy()
shallow[0].append(99)   # nested 的内层也被改了

import copy
deep = copy.deepcopy(nested)  # 完全独立副本

8. 项目开发要点 #