V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
petelin
V2EX  ›  Python

列表推演 比 list 差这么多?

  •  
  •   petelin · 2016-08-05 14:38:29 +08:00 · 2072 次点击
    这是一个创建于 2830 天前的主题,其中的信息可能已经有所发展或是发生改变。

    In [115]: timeit len(list(itertools.repeat(0,10000))) 10000 loops, best of 3: 60.5 µs per loop

    In [116]: timeit len([i for i in itertools.repeat(0,10000)]) 1000 loops, best of 3: 290 µs per loop

    有人解释说 第二个是生成一个[]然后 append 进去的所以慢, w(゚Д゚)w ,那第一个难道不是?他能知道长度?

    2 条回复    2016-08-06 09:49:44 +08:00
    yangtukun1412
        1
    yangtukun1412  
       2016-08-05 15:09:36 +08:00   ❤️ 2
    help(itertools.repeat.__length_hint__)
    necomancer
        2
    necomancer  
       2016-08-06 09:49:44 +08:00
    楼上完美解决问题。
    好像是一个需要不需要推演的问题, itertools 叫高效迭代器看来不是白叫的。
    速度排序:
    In [4]: %timeit len([0] * 10000) #直接写出列表
    10000 loops, best of 3: 25.8 µs per loop
    In [5]: %timeit len(list(itertools.repeat(0,10000))) #这个有 __length_hint__
    10000 loops, best of 3: 49.9 µs per loop
    In [6]: %timeit len([ i for i in itertools.repeat(0, 10000) ]) # list comprehension
    1000 loops, best of 3: 333 µs per loop
    In [7]: %timeit len(list((x for x in itertools.repeat(0, 10000)))) # list(generator)
    1000 loops, best of 3: 642 µs per loop
    如果用 0 for i in range(10000) 会更慢,就不写了。
    所以应该是列表推导的问题。并且 list comprehension 的速度 > list(generator)
    还有更慢的比如 sum(1 for i in generator),不过内存消耗会最小。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   954 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:28 · PVG 02:28 · LAX 11:28 · JFK 14:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.