推荐学习书目
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
WKPlus
V2EX  ›  Python

你觉得优雅的 python 代码片段

  •  
  •   WKPlus · Aug 6, 2015 · 4029 views
    This topic created in 3941 days ago, the information mentioned may be changed or developed.

    刚刚看到这个帖子 /t/210811 有感,代码也不是越短越优雅,那么(这个转折好像并不合适)有没有你觉得能称得上优雅的python代码(写过或看过的都可),最好短一点。

    我先来一个,寻找list中满足某个条件的第一个元素,我写了三个版本:

    版本一:

    target = None
    for e in elements:
        if condition(e):
             target = e
             break
    

    版本二:

    e = [i for i in l if condition(i)][0]  # 至少包含一个这类元素,所以这里不用判断
    

    版本三:

    e = next((i for i in l if condition(i)), None)
    

    版本一缺点:太长
    版本二缺点:效率不高
    暂时没发现版本三的缺点

    8 replies    2015-08-06 23:53:51 +08:00
    realityone
        1
    realityone  
       Aug 6, 2015
    filter(condition, l)
    saber000
        2
    saber000  
       Aug 6, 2015
    昨晚新写的很暴力的lazy import实现:
    https://github.com/MrLYC/ycyc/blob/dev/ycyc/base/lazyutils.py#L80

    def lazy_import(module_name):
    class FakeModule(object):
    def __getattribute__(self, attr):
    module = importlib.import_module(module_name)
    self.__dict__ = module.__dict__
    return getattr(module, attr)

    return FakeModule()

    用法:
    os = lazy_import("os")
    print(os.listdir(".")) # as same as `import os`
    balabala = lazy_import("balabala")
    balabala.xxx() # raise ImportError here
    saber000
        3
    saber000  
       Aug 6, 2015
    @saber000 果不其然缩进跪了,点链接吧
    plqws
        4
    plqws  
       Aug 6, 2015
    待到 python 回调时,js 在丛中笑
    zhuangzhuang1988
        6
    zhuangzhuang1988  
       Aug 6, 2015
    WKPlus
        7
    WKPlus  
    OP
       Aug 6, 2015
    @realityone 用filter和第二个版本一样,改成ifilter和第三个版本一样
    WKPlus
        8
    WKPlus  
    OP
       Aug 6, 2015
    @saber000 恩,蛮有意思的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3185 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 14:07 · PVG 22:07 · LAX 07:07 · JFK 10:07
    ♥ Do have faith in what you're doing.