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

4 python styles

以下几行实际上就像句子一样可读.这样做也似乎非常Pythonic,但我再次知道这种语言,只是寻找风格提示.

for state in states: score += penalty if state == bad else bonus
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 7

那种风​​格在我的工作场所不合适.考虑一下PEP8的这个片段:

通常不鼓励使用复合语句(同一行上的多个语句).

是:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()
Run Code Online (Sandbox Code Playgroud)

而不是:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
Run Code Online (Sandbox Code Playgroud)

所以,在你的情况下:

坏:

for state in states: score += penalty if state == bad else bonus
Run Code Online (Sandbox Code Playgroud)

更好:

for state in states:
    score += penalty if state == bad else bonus
Run Code Online (Sandbox Code Playgroud)

最好:

for state in states:
    if state == bad:
        score += penalty
    else:
        score += bonus
Run Code Online (Sandbox Code Playgroud)

作为设计风格的问题,不一定是编码风格,我宁可看一下存储在映射对象中的特定于状态的分数增量,如下所示:

for state in states:
    score += scores_per_state[state]
Run Code Online (Sandbox Code Playgroud)