将一个多层嵌套的序列展开成一个单层列表 可以写一个包含yield from 语句的递归生成器来轻松解决这个问题. from collections import Iterable def flatten(items, ignore_types=(str, bytes)): for x in items: if isinstance(x, Iterable) and not isinstance(x, ignore_types): yield from flatten(x) else: yield…
读Python基础教程(第二版)后看到了这么一个东西,就是利用递归遍历嵌套结构中的元素. 上代码: #encoding:UTF-8 def flatten(nested): try: #不要迭代类似字符串的对象: try: nested+'' except TypeError: pass else: raise TypeError for sublist in nested: for element in flatten(sublist): yield element except TypeEr…
Python 代码阅读合集介绍:为什么不推荐Python初学者直接看项目源码 本篇阅读的代码实现了展开嵌套列表的功能,将一个嵌套的list展开成一个一维list(不改变原有列表的顺序). 本篇阅读的代码片段来自于30-seconds-of-python. flatten def flatten(lst): return [x for y in lst for x in y] # EXAMPLES flatten([[1,2,3,4],[5,6,7,8]]) # [1, 2, 3, 4, 5, 6…