>>> import timeit
根据官方文档:https://docs.python.org/zh-cn/3/library/itertools.html#itertools.chain
比较常见的有如下三种迭代方式:
>>> timeit.timeit(
... "for x in chain.from_iterable(n):\n"
... " c = x",
... setup="from itertools import chain\n"
... "n = [[1, 3, 5] * 100 for _ in range(100)]",
... number=10000
... )
4.7938309000000014
>>> timeit.timeit(
... "for x in chain(*n):\n"
... " c = x",
... setup="from itertools import chain\n"
... "n = [[1, 3, 5] * 100 for _ in range(100)]",
... number=10000
... )
4.719357599999995
>>> timeit.timeit(
... "for x in n:\n"
... " for xx in x:\n"
... " c = xx",
... setup="n = [[1, 3, 5] * 100 for _ in range(100)]",
... number=10000
... )
4.0301728000000026
通过 Python 3.9 的运行时间来看,直接双层遍历的效果是最高的。
Cpython 源码地址:https://github.com/python/cpython/blob/5871e19942fdcf83653924ae9a849941669c1143/Modules/itertoolsmodule.c