有时我会把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

但这不是很漂亮

你能推荐另一种方法吗?


当前回答

将您的条件打包到列表中,然后执行smth。如:

if False not in Conditions:
    do_something

其他回答

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

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

这里有一种更易读的方法

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

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

“all”和“any”适用于同一类型case的许多条件。但他们总是评估所有条件。如本例所示:

def c1():
    print " Executed c1"
    return False
def c2():
    print " Executed c2"
    return False


print "simple and (aborts early!)"
if c1() and c2():
    pass

print

print "all (executes all :( )"
if all((c1(),c2())):
    pass

print

我建议将和关键字移到第二行,并用两个空格而不是四个空格缩进包含条件的所有行:

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

这正是我在代码中解决这个问题的方法。将关键字作为行中的第一个单词可以使条件更加可读,并且减少空格的数量可以进一步区分条件和操作。

将您的条件打包到列表中,然后执行smth。如:

if False not in Conditions:
    do_something

这里必须有人支持使用垂直空格!:)

if (     cond1 == val1
     and cond2 == val2
     and cond3 == val3
   ):
    do_stuff()

这使每个条件都清晰可见。它还允许更清晰地表达更复杂的条件:

if (    cond1 == val1
     or 
        (     cond2_1 == val2_1
          and cond2_2 >= val2_2
          and cond2_3 != bad2_3
        )
   ):
    do_more_stuff()

是的,为了清晰起见,我们在交易一些垂直房地产。非常值得。