以下几行实际上就像句子一样可读.这样做也似乎非常Pythonic,但我再次知道这种语言,只是寻找风格提示.
for state in states: score += penalty if state == bad else bonus
Run Code Online (Sandbox Code Playgroud)
那种风格在我的工作场所不合适.考虑一下PEP8的这个片段:
通常不鼓励使用复合语句(同一行上的多个语句).
是:
Run Code Online (Sandbox Code Playgroud)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()
所以,在你的情况下:
坏:
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)