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

但这不是很漂亮

你能推荐另一种方法吗?


当前回答

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

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

这适用于“和”和“或”(重要的是它们位于第二行的第一位),但对于其他较长的条件就更不适用了。幸运的是,前者似乎是更常见的情况,而后者往往很容易用临时变量重写。(这通常不难,但在重写时保持“和”/“或”的短路可能很难或不那么明显/可读。)

由于我在你的关于C++的博客文章中发现了这个问题,我将补充我的C++风格是相同的:

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

其他回答

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

if False not in Conditions:
    do_something

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

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

if all(condition):
   do_something

我通常使用:

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

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

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

近年来,我一直倾向于使用所有和任何函数,因为我很少将“与”和“或”进行比较,这很有效,并且具有“早期失败”和生成器理解的额外优势:

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

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

注意:任何一个都像许多或比较,所有都像许多和比较。


这很好地结合了生成器的理解,例如:

# 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!")

更多内容:生成器理解

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

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

这里有一种更易读的方法

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

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