0
点赞
收藏
分享

微信扫一扫

【Python性能优化实例】 itertools.chain 和 itertools.chain.from_iterable


>>> 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​​


举报

相关推荐

0 条评论