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…
将一个多层嵌套的序列展开成一个单层列表 可以写一个包含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…
Given a nested list of integers, implement an iterator to flatten it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Example 1: Input: [[1,1],2,[1,1]] Output: [1,1,2,1,1] Explanation: By calling ne…