Python 三元风格:这种风格是好是坏?

Python Ternary Style: Is this good or bad style?

下面这行几乎像一个句子一样可读。这样做似乎也很 Pythonic,但我再次了解这种语言并且只是在寻找风格提示。

for state in states: score += penalty if state == bad else bonus

这种风格不适合我的工作场所。考虑来自 PEP8 的这个片段:

Compound statements (multiple statements on the same line) are generally discouraged.

Yes:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

Rather not:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

因此,在您的情况下:

差:

for state in states: score += penalty if state == bad else bonus

更好:

for state in states:
    score += penalty if state == bad else bonus

最佳:

for state in states:
    if state == bad:
        score += penalty
    else:
        score += bonus

就设计风格而言,不一定是编码风格,我宁愿看到特定于状态的分数增量存储在映射对象中,如下所示:

for state in states:
    score += scores_per_state[state]

正如 Rob 所说,您确实应该参考 Python 的 PEP 标准。在 Python...

中,有一个庞大的社区致力于定义编码风格的好坏

python.org/dev/peps/pep-0008

我建议从这里开始。

我对上面的建议,尽管非常简洁和紧凑,代码最终还是要维护的。在编写代码时始终假设必须维护代码的人将是一个知道你住在哪里的疯狂斧头杀人犯。

将您的行拆分为每个可读行的一个操作或函数。如果维护起来很痛苦,没人会在意你的代码有多漂亮。

IMO,这是糟糕的风格。 "professional environment" 编码的第一个原则是 "Can someone else maintain my code?"

首先,它违反了 PEP8 中关于在一行中安排代码的几项准则。

其次,它以一种类似于理解的方式组合代码,而不是一个。这是不必要的混淆。

最后,python 中的三元样式本质上有点倒退。与其他语言不同,它使用 value/condition/value,而不是 condition/value/value。除非该演示文稿与您的代码的真实情况相匹配(例如,提供默认值),否则您应该使用一种结构来以正确的顺序表达您想要传达的内容:

for state in states:
    if state == bad:
        score += penalty
    else:
        score += bonus

if/else 语句的方向可能会颠倒 (state != bad),具体取决于代码中涉及的打字量或其他费用。但除此之外,请记住,您正在努力让大约 5 年后进入 "fix this old piece of crap" 的某人(可能是您)的生活更轻松。

您可以使用 sum:

score += sum(penalty if state == bad else bonus
             for state in states)