在Python中,遍历嵌套列表通常使用嵌套的for循环。下面是一个简单的示例,展示了如何遍历一个二维列表(嵌套列表):
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for sublist in nested_list:
for item in sublist:
print(item)
输出结果将会是:
1
2
3
4
5
6
7
8
9
如果你需要遍历更深层次的嵌套列表,比如三维列表,你可以继续添加更多的嵌套for循环:
nested_list_3d = [
[
['a', 'b'],
['c', 'd', 'e', 'f'],
['g', 'h']
],
[
['i', 'j'],
['k', 'l', 'm', 'n'],
['o', 'p']
]
]
for two_d_list in nested_list_3d:
for one_d_list in two_d_list:
for item in one_d_list:
print(item)
输出结果将会是:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
如果你需要处理更复杂的数据结构,比如包含字典的列表,你可以使用递归函数来遍历:
def decompose(com):
types = [list, tuple, set]
tmpType = type(com)
if tmpType in types:
for item in com:
decompose(item)
elif tmpType == dict:
for key, val in com.items():
decompose(val)
else:
print(com)
lis = [["k", ["qwe", 20, {"k1": ["tt", 3, 1]}, 89], "ab"]]
decompose(lis)
以上代码将会递归地遍历列表和字典中的所有元素。