# 列表是:
# - 可变的(Mutable)
# - 有序的(Ordered)
# - 可包含任意数据类型的元素
# - 用方括号 [] 表示
# 创建空列表
empty_list = []
empty_list_v2 = list()
# 标准创建
fruits = ["apple", "banana", "cherry", 123, True]
# 混合数据类型
mixed = [1, "two", 3.0, [4,5], {"name": "Alice"}]
# 生成式创建
squares = [x**2 for x in range(10)] # [0,1,4,9,...,81]
# 重复创建
zeros = [0] * 5 # [0,0,0,0,0]
# 转换其他容器
chars = list("hello") # ['h','e','l','l','o']
# 使用生成器表达式
big_list = list(range(1000000)) # 高效创建百万级列表
fruits = ["apple", "banana", "cherry", "durian"]
# 索引 → 0 1 2 3
print(fruits[0]) # "apple"
print(fruits[2]) # "cherry"
print(fruits[-1]) # "durian" (最后一个元素)
print(fruits[-3]) # "banana" (倒数第三个)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 访问第二行第三列
print(matrix[1][2]) # 6
# 三维列表示例
cube = [
[[1,2], [3,4]],
[[5,6], [7,8]]
]
print(cube[1][0][1]) # 6
numbers = [0,1,2,3,4,5,6,7,8,9]
# 基本切片
print(numbers[2:5]) # [2,3,4] (左闭右开)
print(numbers[:3]) # [0,1,2]
print(numbers[6:]) # [6,7,8,9]
# 步长切片
print(numbers[::2]) # [0,2,4,6,8] (步长2)
print(numbers[::-1]) # 反转列表
# 高级切片
numbers[2:5] = [10,11] # 替换元素 → [0,1,10,11,5,6,7,8,9]
fruits = ["apple", "cherry"]
# 尾部追加
fruits.append("banana") # ["apple","cherry","banana"]
# 指定位置插入
fruits.insert(1, "orange") # ["apple","orange","cherry","banana"]
# 合并列表
fruits.extend(["grape","mango"]) # 添加多个元素
fruits += ["kiwi", "peach"] # 等效操作
# 注意:insert在开头插入效率较低(O(n)时间复杂度)
numbers = [1,2,3,2,4,2,5]
# 按值删除(首个匹配项)
numbers.remove(2) # [1,3,2,4,2,5]
# 按索引删除
del numbers[1] # 删除索引1 → [1,2,4,2,5]
popped = numbers.pop(2) # 删除并返回索引2元素 → popped=4
# 清空列表
numbers.clear() # []
# 删除所有指定元素(列表推导式)
numbers = [x for x in numbers if x != 2]
colors = ["red", "green", "blue"]
# 直接赋值修改
colors[1] = "yellow" # ["red","yellow","blue"]
# 批量修改
colors[0:2] = ["black", "white"] # ["black","white","blue"]
# 条件修改
colors = ["大" if len(c)>3 else c for c in colors]
scores = [85, 92, 78, 90, 92, 88]
# 统计次数
print(scores.count(92)) # 2
# 查找索引
print(scores.index(90)) # 3
# print(scores.index(100)) # 报错 ValueError
# 存在性检查
print(90 in scores) # True
# 直接遍历元素
for fruit in ["apple", "banana", "cherry"]:
print(fruit.upper()) # APPLE, BANANA, CHERRY
# 遍历索引+元素
for index, fruit in enumerate(fruits):
print(f"索引{index}是{fruit}")
# 并行遍历多个列表
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# 反向遍历
for fruit in reversed(fruits):
print(fruit)
# 条件遍历
numbers = [1,2,3,4,5]
squares = [num**2 for num in numbers if num%2==0] # [4,16]
操作 | 时间复杂度 | 说明 |
---|---|---|
索引访问 list[i] | O(1) | 直接访问 |
append() | O(1) | 平均时间复杂度 |
insert(0, x) | O(n) | 开头插入效率低 |
x in list | O(n) | 线性扫描 |
列表合并 list1+list2 | O(k) | k为新列表长度 |
预分配空间:已知大小时提前初始化
# 错误示范
lst = []
for i in range(10000):
lst.append(i)
# 正确做法
lst = [0] * 10000 # 预分配
for i in range(10000):
lst[i] = i
优先选择生成器:大数据处理时节省内存
# 列表推导式(立即生成)
big_list = [x**2 for x in range(1000000)]
# 生成器表达式(惰性计算)
big_gen = (x**2 for x in range(1000000))
深浅拷贝问题
# 浅拷贝
original = [[1,2], [3,4]]
copy = original.copy()
copy[0][0] = 99 # 会影响original!
# 深拷贝
import copy
deep_copy = copy.deepcopy(original)
fruits = ["apple", "banana", "cherry"]
# 基础版
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
# 带异常处理版
index = 0
try:
while True:
print(fruits[index])
index += 1
except IndexError:
pass
特性 | for循环 | while循环 |
---|---|---|
适用场景 | 已知迭代次数/遍历容器 | 条件驱动/未知迭代次数 |
索引控制 | 自动处理 | 需手动管理 |
内存消耗 | 更优(迭代器协议) | 需维护额外变量 |
可读性 | 更高 | 需谨慎处理终止条件 |
修改集合 | 危险(可能跳过元素) | 更灵活但需注意索引变化 |
经典案例对比:
# 查找第一个负数(for循环版)
def find_first_negative_for(nums):
for num in nums:
if num < 0:
return num
return None
# 查找第一个负数(while循环版)
def find_first_negative_while(nums):
index = 0
while index < len(nums):
if nums[index] < 0:
return nums[index]
index += 1
return None
# 危险操作(for循环删除元素)
numbers = [1,2,3,4,5]
for num in numbers:
if num %2 ==0:
numbers.remove(num) # 导致跳过元素!
# 安全方案(while循环倒序删除)
index = len(numbers)-1
while index >=0:
if numbers[index]%2 ==0:
del numbers[index]
index -=1
# 推荐方案(列表推导式)
numbers = [num for num in numbers if num%2!=0]
# 提前终止循环(for-else结构)
def has_duplicate(nums):
seen = []
for num in nums:
if num in seen:
print("发现重复")
break
seen.append(num)
else:
print("无重复元素")
# 利用枚举优化while
index = 0
max_index = len(nums)-1
while index <= max_index:
current = nums[index]
# 处理逻辑...
index +=1
实现函数将两个列表交替合并:
输入:["a","b","c"], [1,2,3]
输出:["a",1,"b",2,"c",3]
参考代码
def alternate_merge(list1, list2):
result = []
i = j = 0
while i < len(list1) or j < len(list2):
if i < len(list1):
result.append(list1[i])
i +=1
if j < len(list2):
result.append(list2[j])
j +=1
return result
实现顺时针螺旋遍历二维列表:
输入:[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
输出:[1,2,3,6,9,8,7,4,5]
参考代码
def spiral_order(matrix):
result = []
while matrix:
# 顶部行
result += matrix.pop(0)
# 右侧列
if matrix and matrix[0]:
for row in matrix:
result.append(row.pop())
# 底部行
if matrix:
result += matrix.pop()[::-1]
# 左侧列
if matrix and matrix[0]:
for row in reversed(matrix):
result.append(row.pop(0))
return result
使用while循环找出最长连续递增子序列:
输入:[1,3,5,4,7]
输出:3(子序列1,3,5)
参考代码
def find_max_consecutive(nums):
if not nums:
return 0
max_len = current = 1
i = 0
while i < len(nums)-1:
if nums[i+1] > nums[i]:
current +=1
max_len = max(max_len, current)
else:
current = 1
i +=1
return max_len
使用while循环实现滑动窗口最大值:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
参考代码
def max_sliding_window(nums, k):
from collections import deque
q = deque()
result = []
i = 0
while i < len(nums):
while q and nums[i] >= nums[q[-1]]:
q.pop()
q.append(i)
if i >= k-1:
result.append(nums[q[0]])
if q[0] == i - k +1:
q.popleft()
i +=1
return result
import timeit
# 测试环境:100,000个元素的列表
setup = "lst = list(range(100000))"
# for循环测试
for_time = timeit.timeit(
"for num in lst: pass",
setup=setup,
number=100
)
# while循环测试
while_time = timeit.timeit(
"i=0\nwhile i,
setup=setup,
number=100
)
print(f"For循环耗时:{for_time:.4f}s")
print(f"While循环耗时:{while_time:.4f}s")
典型结果:
“代码的艺术在于选择最合适的控制流结构。” ——《流畅的Python》
“列表是Python的瑞士军刀,但要用好它需要理解其双刃性。” — Python核心开发者