有时我会把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
但这不是很漂亮
你能推荐另一种方法吗?
您不需要在第二个条件行上使用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
这是《风格指南》,(自2010年以来)建议使用括号。
请原谅我的无知,但我对#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!")
更多内容:生成器理解
我认为@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