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

更好用的 Python 管道!

  •  
  •   abersheeran ·
    abersheeran · 2021-04-19 15:46:18 +08:00 · 1985 次点击
    这是一个创建于 1099 天前的主题,其中的信息可能已经有所发展或是发生改变。

    之前的主题 https://v2ex.com/t/743574

    吸取了大家的建议,做了一个更好用的管道出来。根据测试,性能损耗在纳秒级,我个人觉得应该可以忽略。

    还是老样子,不多说,直接看代码。仓库在 https://github.com/abersheeran/cool

    from functools import reduce
    from cool import F, FF
    
    range(10) | F(filter, lambda x: x % 2) | F(sum) == 25
    
    (1, 2) | FF(lambda x, y: x + y) == 3
    
    range(10) | F(reduce, lambda x, y: x + y) == 45
    range(10) | F(reduce, lambda x, y: x + y, ..., 10) == 55
    
    square = F(pow, ..., 2)
    range(10) | F(map, square) | F(sum) == 285
    
    第 1 条附言  ·  2021-04-19 16:35:09 +08:00

    http://coconut-lang.org/ 写一个可能更清晰一些的对比样例。

    range(10) |> map$(pow$(?, 2)) |> list
    

    上面那个代码等价于下面这个

    range(10) | F(map, F(pow, ..., 2)) | F(list)
    

    另外吐槽一下 coconut 的编译结果,惨不忍睹。我都想写个 Python 超集出来编译一波了(在学了、在学了)。

    5 条回复    2021-04-20 18:20:57 +08:00
    SjwNo1
        1
    SjwNo1  
       2021-04-19 16:18:42 +08:00
    cool
    ... 没太懂,表示占位吗
    abersheeran
        2
    abersheeran  
    OP
       2021-04-19 16:23:42 +08:00   ❤️ 1
    @SjwNo1 是的。在仓库 README 里有解释的。
    hanyceZ
        3
    hanyceZ  
       2021-04-20 13:32:01 +08:00
    给大佬点个赞
    listenerri
        4
    listenerri  
       2021-04-20 18:01:42 +08:00
    不明觉厉,点个赞
    abersheeran
        5
    abersheeran  
    OP
       2021-04-20 18:20:57 +08:00
    @listenerri 用就完事!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5320 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 07:08 · PVG 15:08 · LAX 00:08 · JFK 03:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.