Discuz! Board

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 387|回复: 0

flatten 展平列表操作

[复制链接]

19

主题

11

回帖

255

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
255
发表于 2024-6-19 14:47:01 | 显示全部楼层 |阅读模式
py 中有时候需要展平一个嵌套的列表,偶然发现一个已经实现的工具,位于:parlse.utils.py
  1. from typing import Any, Iterable, Iterator, List


  2. def flatten(x: Iterable[Any]) -> List[Any]:
  3.     """flatten(sequence) -> list
  4.     Returns a single, flat list which contains all elements retrieved
  5.     from the sequence and all recursively contained sub-sequences
  6.     (iterables).
  7.     Examples:
  8.     >>> [1, 2, [3,4], (5,6)]
  9.     [1, 2, [3, 4], (5, 6)]
  10.     >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, (8,9,10)])
  11.     [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]
  12.     >>> flatten(["foo", "bar"])
  13.     ['foo', 'bar']
  14.     >>> flatten(["foo", ["baz", 42], "bar"])
  15.     ['foo', 'baz', 42, 'bar']
  16.     """
  17.     return list(iflatten(x))


  18. def iflatten(x: Iterable[Any]) -> Iterator[Any]:
  19.     """iflatten(sequence) -> Iterator
  20.     Similar to ``.flatten()``, but returns iterator instead"""
  21.     for el in x:
  22.         if _is_listlike(el):
  23.             yield from flatten(el)
  24.         else:
  25.             yield el


  26. def _is_listlike(x: Any) -> bool:
  27.     """
  28.     >>> _is_listlike("foo")
  29.     False
  30.     >>> _is_listlike(5)
  31.     False
  32.     >>> _is_listlike(b"foo")
  33.     False
  34.     >>> _is_listlike([b"foo"])
  35.     True
  36.     >>> _is_listlike((b"foo",))
  37.     True
  38.     >>> _is_listlike({})
  39.     True
  40.     >>> _is_listlike(set())
  41.     True
  42.     >>> _is_listlike((x for x in range(3)))
  43.     True
  44.     >>> _is_listlike(range(5))
  45.     True
  46.     """
  47.     return hasattr(x, "__iter__") and not isinstance(x, (str, bytes))


  48. if __name__ == '__main__':
  49.     print(flatten([[[1, 2, 3, [7, 8]], (42, None)], [4, 5], [6], 7, (8, 9, 10)]))
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|DiscuzX

GMT+8, 2024-10-7 01:23 , Processed in 0.065917 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表