How to shorten long “and” statements?
本问题已经有最佳答案,请猛点这里访问。
我有一个looong的"and"语句,例如:
1 2 | if this == that and this == that and this == that: do this |
如何正确地将这些声明分成几行,以符合PEP-8?
PEP8给出了一个建议:
The preferred way of wrapping long lines is by using Python's implied
line continuation inside parentheses, brackets and braces. Long lines
can be broken over multiple lines by wrapping expressions in
parentheses. These should be used in preference to using a backslash
for line continuation. Make sure to indent the continued line
appropriately. The preferred place to break around a binary operator
is after the operator, not before it.
实例:
1 2 3 4 5 6 7 8 | if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") if width == 0 and height == 0 and (color == 'red' or emphasis is None): raise ValueError("I don't think so -- values are %s, %s" % (width, height)) |
您可以在python中分隔行,但通过插入反斜杠将它们标记为相同的"语义"行:
1 2 3 4 | if this == that \ and this == that \ and this == that: do this |
即使在复杂的条件表达式中有