有时我会把if中的长条件分解成几行。最明显的方法是:

  if (cond1 == 'val1' and cond2 == 'val2' and
      cond3 == 'val3' and cond4 == 'val4'):
      do_something

视觉上不是很吸引人,因为动作与环境融为一体。然而,这是使用4个空格的正确Python缩进的自然方式。

目前我正在使用:

  if (    cond1 == 'val1' and cond2 == 'val2' and
          cond3 == 'val3' and cond4 == 'val4'):
      do_something

但这不是很漂亮

你能推荐另一种方法吗?


当前回答

加上@krawyoti所说的。。。长时间的环境气味难闻,因为它们难以阅读和理解。使用函数或变量可以使代码更清晰。在Python中,我更喜欢使用垂直空格,括起括号,并将逻辑运算符放在每一行的开头,这样表达式看起来不像“浮动”。

conditions_met = (
    cond1 == 'val1' 
    and cond2 == 'val2' 
    and cond3 == 'val3' 
    and cond4 == 'val4'
    )
if conditions_met:
    do_something

如果需要对条件进行多次求值,例如在while循环中,那么最好使用局部函数。

其他回答

在退化情况下,我采用了以下方法,即简单的AND或or。

if all( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):

if any( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):

它剃掉了几个字符,并清楚地表明没有任何微妙的条件。

请原谅我的无知,但我对#Python的了解不如在座的任何人,但我碰巧在3D BIM建模中编写自己的对象脚本时发现了类似的东西,因此我将调整我的算法以适应Python。

我在这里发现的问题是双面的:

我的价值观对于试图破译剧本的人来说似乎很陌生。如果这些值被更改(最有可能),或者如果必须添加新条件(破坏模式),代码维护将付出高昂的代价

要绕过所有这些问题,脚本必须这样运行

param_Val01 = Value 01   #give a meaningful name for param_Val(i) preferable an integer
param_Val02 = Value 02
param_Val03 = Value 03
param_Val04 = Value 04   # and ... etc

conditions = 0           # this is a value placeholder

########
Add script that if true will make:

conditions = conditions + param_Val01   #value of placeholder is updated
########

### repeat as needed


if conditions = param_Val01 + param_Val02 + param_Val03 + param_Val04:
    do something

这种方法的优点:

脚本可读。脚本很容易维护。条件是对表示期望条件的值的和的1比较操作。无需多级条件

希望它能帮助你们

所有同时为if语句提供多条件的回答者都和问题一样难看。你不能通过做同样的事情来解决这个问题。。

即使是PEP 0008的答案也令人反感。

这里有一种更易读的方法

condition = random.randint(0, 100) # to demonstrate
anti_conditions = [42, 67, 12]
if condition not in anti_conditions:
    pass

要我收回我的话吗?让我相信你需要多个条件句,我会把它打印出来,然后吃给你消遣。

当我有一个非常大的if条件时,我更喜欢这种风格:

if (
    expr1
    and (expr2 or expr3)
    and hasattr(thingy1, '__eq__')
    or status=="HappyTimes"
):
    do_stuff()
else:
    do_other_stuff()

我通常做的是:

if (cond1 == 'val1' and cond2 == 'val2' and
    cond3 == 'val3' and cond4 == 'val4'
   ):
    do_something

这样,右括号和冒号可视地标志着我们的状态结束。