795

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

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

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

目前我正在使用:

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

但这不是很漂亮。:-)

你能推荐一种替代方法吗?

4

30 回答 30

893

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

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

不过,这两个都相当丑陋。

也许会丢失括号(尽管样式指南不鼓励这样做)?

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

这是Style Guide,(自 2010 年以来)建议使用括号。

于 2008-10-08T06:34:25.267 回答
140

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

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

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

它刮掉了一些字符,并清楚地表明这种情况没有微妙之处。

于 2008-10-08T10:26:48.247 回答
63

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

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()

是的,为了清晰起见,我们正在权衡一些垂直空间。海事组织非常值得。

于 2008-10-08T14:55:02.933 回答
50

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

if (
    expr1
    and (expr2 or expr3)
    and hasattr(thingy1, '__eq__')
    or status=="HappyTimes"
):
    do_stuff()
else:
    do_other_stuff()
于 2008-10-08T08:39:58.620 回答
28

这是我个人的看法:长条件(在我看来)是一种代码味道,建议重构为布尔返回函数/方法。例如:

def is_action__required(...):
    return (cond1 == 'val1' and cond2 == 'val2'
            and cond3 == 'val3' and cond4 == 'val4')

现在,如果我找到一种使多行条件看起来不错的方法,我可能会发现自己满足于拥有它们并跳过重构。

另一方面,让它们扰乱我的审美感会成为重构的动力。

因此,我的结论是,多行条件应该看起来很难看,这是避免它们的动力。

于 2011-01-14T10:50:32.403 回答
26

这并没有太大改善,但是...

allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and
                 cond3 == 'val3' and cond4 == 'val4')

if allCondsAreOK:
   do_something
于 2008-10-08T06:31:54.790 回答
19

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

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

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

于 2008-10-08T07:19:09.780 回答
16

似乎值得引用PEP 0008(Python 的官方风格指南),因为它以适度的长度评论了这个问题:

当 - 语句的条件部分if足够长以至于需要跨多行编写时,值得注意的是,两个字符的关键字(即if)加上一个空格,再加上一个左括号会创建一个自然的 4-多行条件的后续行的空格缩进。这可能会与嵌套在 - 语句内的缩进代码套件产生视觉冲突,该代码if也自然缩进为 4 个空格。这个 PEP 没有明确说明如何(或是否)进一步在视觉上将这些条件行与 - 语句内的嵌套套件区分开来if。在这种情况下可接受的选项包括但不限于:

# No extra indentation.
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

注意上面引用中的“不限于”;除了风格指南中建议的方法外,该问题的其他答案中建议的一些方法也是可以接受的。

于 2015-07-05T14:15:27.350 回答
8

这就是我所做的,记住“all”和“any”接受一个可迭代的,所以我只是把一个长条件放在一个列表中,让“all”完成工作。

condition = [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4']

if all(condition):
   do_something
于 2014-11-19T03:34:33.477 回答
5

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

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

如果需要多次评估条件,例如在while循环中,则最好使用局部函数。

于 2011-01-19T20:53:39.250 回答
5

就个人而言,我喜欢为长的 if 语句添加意义。我必须搜索代码才能找到合适的示例,但这是我想到的第一个示例:假设我碰巧遇到了一些古怪的逻辑,我想根据许多变量显示某个页面。

英语:“如果登录用户不是管理员教师,而只是普通教师,本身又不是学生……”

if not user.isAdmin() and user.isTeacher() and not user.isStudent():
    doSomething()

当然这可能看起来不错,但是阅读那些 if 语句是很多工作。我们如何将逻辑分配给有意义的标签。“标签”实际上是变量名:

displayTeacherPanel = not user.isAdmin() and user.isTeacher() and not user.isStudent()
if displayTeacherPanel:
    showTeacherPanel()

这可能看起来很愚蠢,但您可能还有另一种情况,您只希望显示另一个项目,当且仅当您正在显示教师面板或默认情况下用户有权访问该其他特定面板时:

if displayTeacherPanel or user.canSeeSpecialPanel():
    showSpecialPanel()

尝试在不使用变量来存储和标记逻辑的情况下编写上述条件,不仅会得到一个非常混乱、难以阅读的逻辑语句,而且还会重复自己。虽然有合理的例外,但请记住:不要重复自己(DRY)。

于 2013-03-07T06:24:12.010 回答
4

我很惊讶没有看到我喜欢的解决方案,

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

因为and是一个关键字,所以它会被我的编辑器突出显示,并且看起来与它下面的 do_something 完全不同。

于 2011-01-14T14:50:50.417 回答
4

简单明了,也通过了 pep8 检查:

if (
    cond1 and
    cond2
):
    print("Hello World!")

最近,我更喜欢allandany函数,因为我很少混合 And 和 Or 比较,这很好用,并且具有生成器理解的早期失败的额外优势:

if all([
    cond1,
    cond2,
]):
    print("Hello World!")

只要记住传递一个可迭代的!传入 N 参数是不正确的。

注意:any就像许多or比较,all就像许多and比较。


这与生成器理解很好地结合在一起,例如:

# Check if every string in a list contains a substring:
my_list = [
    'a substring is like a string', 
    'another substring'
]

if all('substring' in item for item in my_list):
   print("Hello World!")

# or

if all(
    'substring' in item
    for item in my_list
):
    print("Hello World!")

更多信息:生成器理解

于 2014-11-24T07:44:29.843 回答
3

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

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
于 2008-10-08T10:38:37.490 回答
3

(我稍微修改了标识符,因为固定宽度的名称不代表真实代码——至少不是我遇到的真实代码——并且会掩盖示例的可读性。)

if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "val4"):
    do_something

这适用于“and”和“or”(重要的是它们在第二行的第一个),但对于其他长条件则更不适用。幸运的是,前者似乎更常见,而后者通常很容易用临时变量重写。(通常并不难,但在重写时保持“and”/“or”的短路可能很困难或不太明显/可读性。)

由于我从您关于 C++ 的博客文章中发现了这个问题,因此我将包括我的 C++ 风格是相同的:

if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "val4") {
    do_something
}
于 2011-01-14T08:33:47.987 回答
2

如果我们只在条件和正文之间插入一个额外的空行并以规范的方式完成其余的工作呢?

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

    do_something

ps 我总是使用制表符,而不是空格;我无法微调...

于 2008-10-09T02:45:40.300 回答
2

我通常做的是:

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

这样,右大括号和冒号在视觉上标志着我们条件的结束。

于 2014-08-01T17:53:44.293 回答
2

我知道这个线程很旧,但我有一些 Python 2.7 代码和 PyCharm (4.5) 仍然抱怨这种情况:

if foo is not None:
    if (cond1 == 'val1' and cond2 == 'val2' and
        cond3 == 'val3' and cond4 == 'val4'):
            # some comment about do_something
            do_something

即使 PEP8 警告“视觉缩进的行与下一个逻辑行的缩进相同”,实际代码完全可以吗?这不是“过度缩进”?

...有时我希望 Python 能咬紧牙关,只带花括号。我想知道这些年来由于意外的错误缩进而意外引入了多少错误......

于 2016-11-29T17:12:15.843 回答
2

所有还为 if 语句提供多条件的受访者都与所提出的问题一样丑陋。你不能通过做同样的事情来解决这个问题..

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

这是一种更具可读性的方法

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

要我吃我的话?说服我您需要多条件,我会逐字打印并吃掉它以供您娱乐。

于 2017-06-17T06:16:15.323 回答
2

我认为@zkanda 的解决方案只要稍加改动就可以了。如果您在各自的列表中有条件和值,则可以使用列表推导进行比较,这将使添加条件/值对的事情更加通用。

conditions = [1, 2, 3, 4]
values = [1, 2, 3, 4]
if all([c==v for c, v in zip(conditions, values)]):
    # do something

如果我确实想对这样的语句进行硬编码,为了便于阅读,我会这样写:

if (condition1==value1) and (condition2==value2) and \
   (condition3==value3) and (condition4==value4):

iand只是用操作员抛出另一个解决方案:

proceed = True
for c, v in zip(conditions, values):
    proceed &= c==v

if proceed:
    # do something
于 2017-07-21T13:03:27.863 回答
1

为了完整起见,只是其他一些随机的想法。如果它们对您有用,请使用它们。否则,您最好尝试其他方法。

你也可以用字典来做到这一点:

>>> x = {'cond1' : 'val1', 'cond2' : 'val2'}
>>> y = {'cond1' : 'val1', 'cond2' : 'val2'}
>>> x == y
True

此选项更复杂,但您可能也会发现它很有用:

class Klass(object):
    def __init__(self, some_vars):
        #initialize conditions here
    def __nonzero__(self):
        return (self.cond1 == 'val1' and self.cond2 == 'val2' and
                self.cond3 == 'val3' and self.cond4 == 'val4')

foo = Klass()
if foo:
    print "foo is true!"
else:
    print "foo is false!"

不知道这是否适合您,但这是另一个需要考虑的选择。这是另一种方法:

class Klass(object):
    def __init__(self):
        #initialize conditions here
    def __eq__(self):
        return (self.cond1 == 'val1' and self.cond2 == 'val2' and
               self.cond3 == 'val3' and self.cond4 == 'val4')

x = Klass(some_values)
y = Klass(some_other_values)
if x == y:
    print 'x == y'
else:
    print 'x!=y'

最后两个我没有测试过,但如果你想要这样做,这些概念应该足以让你继续前进。

(为了记录,如果这只是一次性的事情,你可能最好使用你一开始提出的方法。如果你在很多地方进行比较,这些方法可能会增强可读性,足以让你对他们有点老套这一事实并不感到难过。)

于 2008-10-08T17:26:00.320 回答
1

我也一直在努力寻找一种体面的方法来做到这一点,所以我只是想出了一个主意(不是灵丹妙药,因为这主要是一个品味问题)。

if bool(condition1 and
        condition2 and
        ...
        conditionN):
    foo()
    bar()

与我见过的其他解决方案相比,我发现这个解决方案有一些优点,即,你得到了一个额外的 4 个缩进空间(布尔),允许所有条件垂直排列,并且 if 语句的主体可以缩进一种清晰(ish)的方式。这也保留了布尔运算符的短路评估的好处,但当然增加了基本上什么都不做的函数调用的开销。您可以(有效地)争辩说,任何返回其参数的函数都可以在这里使用而不是 bool,但就像我说的,这只是一个想法,最终是一个品味问题。

有趣的是,当我写这篇文章并思考“问题”时,我想到了另一个想法,它消除了函数调用的开销。为什么不通过使用额外的括号来表明我们将要输入一个复杂的条件呢?再说 2 个,以给出子条件相对于 if 语句主体的 2 个空格缩进。例子:

if (((foo and
      bar and
      frob and
      ninja_bear))):
    do_stuff()

我有点喜欢这样,因为当你看到它时,你的脑海中会立刻响起一个铃声,说“嘿,这里发生了一件复杂的事情!” . 是的,我知道括号对可读性没有帮助,但是这些条件应该很少出现,当它们出现时,无论如何你都必须停下来仔细阅读它们(因为它们很复杂)。

无论如何,还有两个我在这里没有看到的建议。希望这可以帮助某人:)

于 2014-12-03T19:19:18.710 回答
1

你可以把它分成两行

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

甚至一次添加一个条件。这样,至少它将杂乱与if.

于 2016-08-04T19:30:45.363 回答
0

把你的条件打包成一个列表,然后做某事。像:

if False not in Conditions:
    do_something
于 2010-06-09T09:23:43.607 回答
0

我发现当我有长条件时,我经常有一个短代码体。在这种情况下,我只是双缩进正文,因此:

if (cond1 == 'val1' and cond2 == 'val2' and
    cond3 == 'val3' and cond4 == 'val4'):
        do_something
于 2011-09-22T08:31:27.493 回答
0
  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

在这种情况下,没有理由缩进应该是 4 的倍数,例如,请参阅“与开头分隔符对齐”:

http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Indentation#Indentation

于 2012-03-13T11:13:19.927 回答
0

这是另一种方法:

cond_list = ['cond1 == "val1"','cond2=="val2"','cond3=="val3"','cond4=="val4"']
if all([eval(i) for i in cond_list]):
 do something

这也使得添加另一个条件变得容易,而无需通过简单地将另一个条件附加到列表中来更改 if 语句:

cond_list.append('cond5=="val5"')
于 2014-10-16T22:08:03.513 回答
0

我通常使用:

if ((cond1 == 'val1' and cond2 == 'val2' and
     cond3 == 'val3' and cond4 == 'val4')):
    do_something()
于 2015-03-05T00:12:32.823 回答
0

如果我们的 if 和 else 条件必须在其中执行多个语句,那么我们可以像下面这样写。每当我们有 if else 示例时,其中都有一个语句。

谢谢它对我有用。

#!/usr/bin/python
import sys
numberOfArgument =len(sys.argv)
weblogic_username =''
weblogic_password = ''
weblogic_admin_server_host =''
weblogic_admin_server_port =''


if numberOfArgument == 5:
        weblogic_username = sys.argv[1]
        weblogic_password = sys.argv[2]
        weblogic_admin_server_host =sys.argv[3]
        weblogic_admin_server_port=sys.argv[4]
elif numberOfArgument <5:
        print " weblogic UserName, weblogic Password and weblogic host details are Mandatory like, defalutUser, passwordForDefaultUser, t3s://server.domainname:7001 ."
        weblogic_username = raw_input("Enter Weblogic user Name")
        weblogic_password = raw_input('Enter Weblogic user Password')
        weblogic_admin_server_host = raw_input('Enter Weblogic admin host ')
        weblogic_admin_server_port = raw_input('Enter Weblogic admin port')
#enfelif
#endIf
于 2015-12-06T12:27:55.893 回答
0

请原谅我的菜鸟,但碰巧我不像你们这里的任何人一样了解#Python,但碰巧我在 3D BIM 建模中编写自己的对象脚本时发现了类似的东西,所以我将调整我的算法以蟒蛇。

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

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

绕过所有这些问题,你的脚本必须像这样

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. 脚本可读。

  2. 脚本易于维护。

  3. conditions 是对表示所需条件的值之和的 1 比较操作。
  4. 无需多级条件

希望对大家有帮助

于 2019-10-25T17:28:13.220 回答