python遍历嵌套列表

用生成器函数遍历一个嵌套列表

假设有如下嵌套列表:

items = [1, 2, [3, 4, [5, 6], 7], 8]

想要把列表中所有元素输出为一系列单独的值(而不是有的是值,有的是子列表)

1
2
3
4
5
6
7
8
from collections import Iterable

def get_index(items, ignore_type=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_type):
yield from get_index(x)
else:
yield x

效果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for x in get_index(items):
print(x)

# 输出
1
2
3
4
5
6
7
8

Process finished with exit code 0

使用isinstance判断子元素是否可迭代,如果可迭代,使用yield from将这个可迭代对象进行递归,直到所有元素产出

该方法来自《Python Cookbook》一书

文章目录
|