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

分享文章《为什么 Python 、Go 和 Rust 都不支持三元运算符?》

  •  
  •   chinesehuazhou · Apr 3, 2023 · 3313 views
    This topic created in 1164 days ago, the information mentioned may be changed or developed.

    避坑说明:

    1.一句话回答:Python 在经过一番波折后,最后设计出了与众不同的条件表达式。Go 语言明确表示不支持三元运算符。Rust 先设计后舍去,主要的原因在于 if 表达式的语言基础。

    2.文章主要梳理 PEP-308 内容,介绍 Python 引入条件表达式的过程:Python 没有设计三元运算符“?:”,主要是因为它不符合 Python 明确直观的设计风格。最后采用 X if C else Y 这种设计,主要的意图其实是消除“and-or”写法的隐患,这种设计简明易读,而且还有<expression> if <condition> 简化写法的妙用。

    链接 1:出自个人博客,无需关注阅读 https://pythoncat.top/posts/2023-04-03-condition

    链接 2: 来自公众号,如果你喜欢文章,请给个关注哈 https://mp.weixin.qq.com/s/YQ6MmefRPW7pNg3N1VAcTQ

    Supplement 1  ·  Apr 7, 2023
    有个严重 bug ,博客已更正。公众号已删除重发:
    https://mp.weixin.qq.com/s/wfK7SpRqre2n5IEUAHLQ8Q
    10 replies    2023-04-12 01:13:48 +08:00
    ysw
        1
    ysw  
       Apr 4, 2023
    感觉三元表达式就是太丑了,容易看错
    kkocdko
        2
    kkocdko  
       Apr 4, 2023
    其实如果使用得当就还好,但是现代编程语言通常都希望在语言设计层面避免瞎写,也不错啦
    LeeReamond
        3
    LeeReamond  
       Apr 4, 2023   ❤️ 6
    三元表达式:还算是个人
    嵌套三元表达式:地狱来客
    hongzhangliu
        4
    hongzhangliu  
       Apr 4, 2023
    看完了,写的挺清晰的。一个问题,<expression> if <condition> 这种方式,在什么情形下可用?直接在 ipython 里测试了一下,报语法错误
    wliansheng
        5
    wliansheng  
       Apr 4, 2023
    @hongzhangliu 文章里面写的很清楚 X if C else Y
    acherkrau
        6
    acherkrau  
       Apr 4, 2023
    刚在公众号看过,原来作者在 v2 也有帐号
    dragondove
        7
    dragondove  
       Apr 4, 2023
    有三元运算符的语言在设计初期都没有 if/switch expression ,可读性和可维护性上应该是 switch expression 最好。
    cond ? a : b 改为 switch(cond) { true -> a; false -> b; } (最好是 cond 里直接包含一个变量用 switch )就是写起来长一点
    chinesehuazhou
        8
    chinesehuazhou  
    OP
       Apr 4, 2023
    @hongzhangliu 刚试了确实不行,但我印象中是可以的。。。脑子混了
    junkun
        9
    junkun  
       Apr 5, 2023
    个人感觉是 C “带坏”了很多语言的设计,三元运算符的问题都是因为 if 块或者 Block 没有返回值。
    whitewinds
        10
    whitewinds  
       Apr 12, 2023
    @hongzhangliu 生成器和推导式里面可以只写 if ,当然 if 前面并不是一个 <expression>
    (print(1) for i in range(10) if i % 2)
    [print(1) for i in range(10) if i % 2]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   931 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 22:13 · PVG 06:13 · LAX 15:13 · JFK 18:13
    ♥ Do have faith in what you're doing.