2025-09-10:仓库迁移
This commit is contained in:
18
4.迭代器与生成器/14.扁平化处理嵌套型的序列.py
Normal file
18
4.迭代器与生成器/14.扁平化处理嵌套型的序列.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from collections import Iterable
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
# 将复杂的序列扁平化,使用递归来脱壳
|
||||
def flatten(items, ignore=(str, bytes)):
|
||||
for item in items:
|
||||
# 要进行递归,首先这个元素要是可迭代的,其次它不能是字符串或二进制串
|
||||
if isinstance(item, Iterable) and not isinstance(item, ignore):
|
||||
# yield from 将请求转发到flatten函数返回的迭代器进行嵌套,避免再写for循环
|
||||
# yield from 在后面的协程和基于生成器的并发程序里有重要作用
|
||||
yield from flatten(item, ignore)
|
||||
else:
|
||||
yield item
|
||||
|
||||
a = [1, 2, [3, 4, [5, 6], 7], 8]
|
||||
for item in flatten(a):
|
||||
print(item)
|
Reference in New Issue
Block a user