本文目录导读:

我来详细介绍Python列表嵌套的多层操作方法和案例。
基础二维列表操作
# 创建二维列表(3x3矩阵)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 访问元素
print(matrix[1][2]) # 访问第2行第3列:6
print(matrix[0][0]) # 访问第1行第1列:1
# 遍历二维列表
for row in matrix:
for item in row:
print(item, end=" ")
print()
# 输出:1 2 3
# 4 5 6
# 7 8 9
三维列表操作
# 创建三维列表
three_d = [
[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
[[9, 10], [11, 12]]
]
# 访问元素
print(three_d[1][0][1]) # 访问第2个面,第1行,第2列:6
print(three_d[2][1][0]) # 访问第3个面,第2行,第1列:11
# 遍历三维列表
for i, layer in enumerate(three_d):
print(f"第{i+1}层:")
for row in layer:
print(row)
print()
不规则嵌套列表
# 不同深度的嵌套
nested_list = [
[1, 2, [3, 4, 5]],
[6, [7, [8, 9]], 10],
11,
[12, 13]
]
# 递归遍历处理不规则嵌套
def flatten_recursive(lst):
"""递归展平列表"""
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten_recursive(item))
else:
result.append(item)
return result
print(flatten_recursive(nested_list))
# 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
操作案例:学生成绩管理
# 多层嵌套表示学生信息
students = [
{
"name": "张三",
"scores": [85, 92, 78],
"details": {
"age": 18,
"class": "1班",
"subjects": ["数学", "语文", "英语"]
}
},
{
"name": "李四",
"scores": [90, 88, 95],
"details": {
"age": 19,
"class": "2班",
"subjects": ["数学", "语文", "英语"]
}
}
]
# 遍历和操作
for student in students:
name = student["name"]
avg_score = sum(student["scores"]) / len(student["scores"])
class_name = student["details"]["class"]
print(f"{name} ({class_name}): 平均分 {avg_score:.2f}")
# 修改嵌套数据
students[0]["scores"][2] = 82 # 修改第三科成绩
print(f"更新后张三成绩: {students[0]['scores']}")
实用操作技巧
# 创建多层嵌套列表并初始化
def create_nested_list(dimensions, default_value=0):
"""创建指定维度的嵌套列表"""
if len(dimensions) == 0:
return default_value
return [create_nested_list(dimensions[1:], default_value)
for _ in range(dimensions[0])]
# 创建3x4x2的三维列表
result = create_nested_list([3, 4, 2], 0)
print(result)
# 列表推导式处理嵌套
matrix = [[j for j in range(3)] for i in range(3)]
print(matrix) # [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
# 深拷贝避免引用问题
import copy
original = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(original)
deep_copy[0][0] = 99
print(f"原始: {original}") # [[1, 2], [3, 4]]
print(f"副本: {deep_copy}") # [[99, 2], [3, 4]]
常见操作函数
def get_nested_value(data, keys):
"""安全获取嵌套列表/字典的值"""
for key in keys:
try:
data = data[key]
except (IndexError, KeyError, TypeError):
return None
return data
def set_nested_value(data, keys, value):
"""设置嵌套列表/字典的值"""
current = data
for key in keys[:-1]:
current = current[key]
current[keys[-1]] = value
# 使用示例
config = {
"database": {
"host": "localhost",
"port": 5432,
"options": ["ssl", "timeout"]
}
}
# 获取深层值
port = get_nested_value(config, ["database", "port"])
print(f"数据库端口: {port}") # 5432
# 修改深层值
set_nested_value(config, ["database", "options", 0], "tls")
print(config["database"]["options"]) # ['tls', 'timeout']
实际应用案例:树形结构
# 文件系统树形结构
file_system = {
"root": {
"home": {
"user1": ["file1.txt", "file2.py"],
"user2": ["doc.md"]
},
"etc": {
"config": ["settings.conf", "network.conf"],
"init.d": ["apache.sh"]
},
"var": {
"log": ["error.log", "access.log"],
"cache": []
}
}
}
def print_directory_tree(structure, indent=0):
"""递归打印文件系统树"""
for key, value in structure.items():
if isinstance(value, dict):
print(" " * indent + f"📁 {key}/")
print_directory_tree(value, indent + 2)
else:
for file in value:
print(" " * indent + f"📄 {file}")
print_directory_tree(file_system)
这些案例覆盖了常见的数据结构嵌套场景,如果需要处理更复杂的情况,建议:
- 使用递归处理不规则嵌套
- 注意深拷贝和浅拷贝的区别
- 使用函数封装复杂的访问逻辑
- 适当使用异常处理保证代码健壮性