30秒学会 Python 片段 · 2023年10月16日

30秒学会 Python 片段 – Deep flatten list

Deep flattens a list.

  • Use recursion.
  • Use isinstance() with collections.abc.Iterable to check if an element is iterable.
  • If it is iterable, apply deep_flatten() recursively, otherwise return [lst].

代码实现

from collections.abc import Iterable

def deep_flatten(lst):
  return ([a for i in lst for a in
          deep_flatten(i)] if isinstance(lst, Iterable) else [lst])

使用样例

deep_flatten([1, [2], [[3], 4], 5]) # [1, 2, 3, 4, 5]

翻译自:https://www.30secondsofcode.org/python/s/deep-flatten