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

你觉得优雅的 python 代码片段

  •  
  •   WKPlus · 2015-08-06 14:07:12 +08:00 · 3164 次点击
    这是一个创建于 3179 天前的主题,其中的信息可能已经有所发展或是发生改变。

    刚刚看到这个帖子 /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 条回复    2015-08-06 23:53:51 +08:00
    realityone
        1
    realityone  
       2015-08-06 15:35:28 +08:00
    filter(condition, l)
    saber000
        2
    saber000  
       2015-08-06 17:20:15 +08:00
    昨晚新写的很暴力的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  
       2015-08-06 17:21:03 +08:00
    @saber000 果不其然缩进跪了,点链接吧
    plqws
        4
    plqws  
       2015-08-06 18:04:55 +08:00
    待到 python 回调时,js 在丛中笑
    zhuangzhuang1988
        5
    zhuangzhuang1988  
       2015-08-06 23:06:28 +08:00
    zhuangzhuang1988
        6
    zhuangzhuang1988  
       2015-08-06 23:18:08 +08:00
    WKPlus
        7
    WKPlus  
    OP
       2015-08-06 23:41:55 +08:00
    @realityone 用filter和第二个版本一样,改成ifilter和第三个版本一样
    WKPlus
        8
    WKPlus  
    OP
       2015-08-06 23:53:51 +08:00
    @saber000 恩,蛮有意思的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5242 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:20 · PVG 17:20 · LAX 02:20 · JFK 05:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.