
刚刚看到这个帖子 /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) 版本一缺点:太长
版本二缺点:效率不高
暂时没发现版本三的缺点
1 realityone 2015 年 8 月 6 日 filter(condition, l) |
2 saber000 2015 年 8 月 6 日 昨晚新写的很暴力的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 |
4 plqws 2015 年 8 月 6 日 待到 python 回调时,js 在丛中笑 |
5 zhuangzhuang1988 2015 年 8 月 6 日 |
6 zhuangzhuang1988 2015 年 8 月 6 日 |
7 WKPlus OP @realityone 用filter和第二个版本一样,改成ifilter和第三个版本一样 |