假设您在 python 中有一个 if 语句,如下所示:
if not "string1" in item and not "string2" in item and not "string3" in item and not "string4" in item:
doSomething(item)
有没有办法将 if 语句分成多行?像这样:
if not "string1" in item
and not "string2" in item
and not "string3 in item
and not "string4" in item:
doSomething(item)
这可能吗?是否有一种不同的、更“pythonic”的方式来使它更具可读性?
请您参考如下方法:
一般来说,当你想把一个表达式分成多行时,使用圆括号:
if (not "string1" in item
and not "string2" in item
and not "string3" in item
and not "string4" in item):
doSomething(item)
此推荐直接来自 Python's style guide (PEP 8) :
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses.
但请注意,在这种情况下,您有更好的选择:
if not any(s in item for s in ("string1", "string2", "string3", "string4")):
doSomething(item)
