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
talentsnail
V2EX  ›  Python

提问:两种python写法的执行效率会相差很大吗?

  •  
  •   talentsnail · 2013-04-24 00:20:43 +08:00 · 3324 次点击
    这是一个创建于 4048 天前的主题,其中的信息可能已经有所发展或是发生改变。
    1.

    [ x for x in some_list if x % 2 == 0 ]

    2.
    list=[]
    for x in some_list:
    if x%2==O:
    list.append(x)

    这两种写法的执行效率相差会很明显嘛?
    8 条回复    1970-01-01 08:00:00 +08:00
    swulling
        1
    swulling  
       2013-04-24 00:31:35 +08:00
    没有,两个都是iterator

    前者更好用,我喜欢
    adieu
        2
    adieu  
       2013-04-24 00:54:20 +08:00
    应该是第一个写法效率高,参见 https://gist.github.com/anonymous/5445383

    第二个写法会用到function call,对效率影响比较大

    话说其实测一下应该很容易比较出来
    mengzhuo
        3
    mengzhuo  
       2013-04-24 01:12:30 +08:00
    第一种是Python的C实现,数据量小的话比第二种快70倍左右
    而且==0 可以不写了
    [ x for x in some_list if x % 2]
    leiz
        4
    leiz  
       2013-04-24 01:43:19 +08:00
    @mengzhuo 有==0是判定双数,没有是是判定单数
    talentsnail
        5
    talentsnail  
    OP
       2013-04-24 08:43:57 +08:00
    @swulling
    @adieu
    @mengzhuo
    @leiz 谢谢大家啦:)
    yangxin0
        6
    yangxin0  
       2013-04-24 10:00:10 +08:00
    第一条是以C语言执行,第二条是解释执行。
    mengzhuo
        7
    mengzhuo  
       2013-04-24 11:00:34 +08:00
    @leiz 谢谢指正,我太粗心了

    LZ也要小心
    0%2 #0 -> False
    1%2 #1 -> True

    那就应该改成
    [ x for x in some_list if not x % 2]
    不过这样不如
    [ x for x in some_list if x%2 == 0]
    看得清
    guotie
        8
    guotie  
       2013-04-24 11:54:55 +08:00   ❤️ 1
    实测如下:
    len(list) f1 f2
    100000 0.006 0.009
    1000000 0.07 0.103
    10000000 0.727 1.052
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1295 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 23:21 · PVG 07:21 · LAX 16:21 · JFK 19:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.