Python样式:IF中的多行条件 [英] Python style: multiple-line conditions in IFs

查看:196
本文介绍了Python样式:IF中的多行条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我将IF中的长条件分解成几行。最明显的做法是:

Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:

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

在视觉上不是非常非常有吸引力,因为动作与条件混合。但是,这是使用正确的Python缩进4个空格的自然方式。

Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.

目前我使用的是:

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

但这不是很漂亮。 : - )

But this isn't very pretty. :-)

您可以推荐一种替代方法吗?

Can you recommend an alternative way ?

推荐答案

您不需要在第二个条件行上使用4个空格。可能使用:

You don't need to use 4 spaces on your second conditional line. Maybe use:

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

t忘记空格比你想象的更灵活:

Also, don't forget the whitespace is more flexible than you might think:

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

这两个都是相当丑陋的。

Both of those are fairly ugly though.

可能会丢失括号( Style Guide 不鼓励这样做)?

Maybe lose the brackets (the Style Guide discourages this though)?

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

这至少给你一些区别。

甚至:

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

我想我更喜欢:

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

这是样式指南,自2010年以来,建议使用括号。

Here's the Style Guide, which (since 2010) recommends using brackets.

这篇关于Python样式:IF中的多行条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆