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)
<generator object flatten at 0x73bd9c>
>>> 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']
"""

相关文章:

  • 2022-01-20
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2021-12-30
  • 2021-10-18
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-27
  • 2021-07-30
  • 2021-11-18
  • 2021-08-06
  • 2021-07-30
  • 2021-12-16
相关资源
相似解决方案