from collections import Iterable
def flatten(items):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
yield from flatten(x)
else:
yield x
"""
>>> items = [1, 2, [3, 4, [5, 6], 7], 8]
>>> flatten(items)
>>> list(flatten(items))
[1, 2, 3, 4, 5, 6, 7, 8]
>>> mixed_bag = [1, 'spam', 2, [3, 'eggs', 4], {'x': 1, 'y': 2}]
>>> list(flatten(mixed_bag))
[1, 'spam', 2, 3, 'eggs', 4, 'y', 'x']
"""
Python中flatten用法
Python中flatten用法 原创 2014年04月16日 10:20:02 标签: Python / flatten 22667 一.用在数组 >>> a = [[1,3],[ ...