Python展开嵌套序列.md
2019-04-20

Python 展开嵌套序列


可以通过 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 x

items = [1, 2, [3, 4, [5, 6], 7], 8]
# 结果未 1 2 3 4 5 6 7 8
for x in flatten(items):
  print(x)

isinstance(x, Iterable) 会检查某个元素是否可迭代,如果可迭代,yield from 会返回所有 项的值。

此外 igonre_types 还可以让你避免展开某些类型,比如字符串

items = ['Dave', 'Paula', ['Thomas', 'Lewis']]
for x in flatten(items):
  print(x)
Dave
Paula
Thomas
Lewis