__init__.py 文件源码

python
阅读 19 收藏 0 点赞 0 评论 0

项目:odin 作者: imito 项目源码 文件源码
def flatten_list(x, level=None):
  """
  Parameters
  ----------
  level: int, or None
      how deep the function go into element of x to search for list and
      flatten it. If None is given, flatten all list found.

  Example
  -------
  >>> l = [1, 2, 3, [4], [[5], [6]], [[7], [[8], [9]]]]
  >>> print(flatten_list(l, level=1))
  >>> # [1, 2, 3, 4, [5], [6], [7], [[8], [9]]]
  >>> print(flatten_list(l, level=2))
  >>> # [1, 2, 3, 4, 5, 6, 7, [8], [9]]
  >>> print(flatten_list(l, level=None))
  >>> # [1, 2, 3, 4, 5, 6, 7, 8, 9]
  """
  if isinstance(x, Iterator):
    x = list(x)
  if level is None:
    level = 10e8
  if not isinstance(x, (tuple, list)):
    return [x]
  if any(isinstance(i, (tuple, list)) for i in x):
    _ = []
    for i in x:
      if isinstance(i, (tuple, list)) and level > 0:
        _ += flatten_list(i, level - 1)
      else:
        _.append(i)
    return _
  return x


# ===========================================================================
# Python
# ===========================================================================
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号