Files
Python_CookBook_repo/4.迭代器与生成器/14.扁平化处理嵌套型的序列.py
2025-09-10 16:12:45 +08:00

19 lines
776 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)