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

但这不是很漂亮

你能推荐另一种方法吗?


当前回答

请原谅我的无知,但我对#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比较操作。无需多级条件

希望它能帮助你们

其他回答

为了完整起见,只需要一些其他随意的想法。如果它们对你有用,就使用它们。否则,你最好尝试其他方法。

你也可以用字典这样做:

>>> 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'

最后两个我还没有测试过,但如果你想使用这些概念,那么这些概念应该足以让你继续下去。

(顺便说一句,如果这只是一次性的事情,你可能会更好地使用你最初提出的方法。如果你在很多地方进行比较,这些方法可能会增强可读性,让你不会因为它们有点粗糙而感到很糟糕。)

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

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

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

如果我们的if-anelse条件必须在其中执行多个语句,那么我们可以像下面这样写。每当我们有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

请原谅我的无知,但我对#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比较操作。无需多级条件

希望它能帮助你们

简单明了,也通过了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!")

更多内容:生成器理解