[英]Pythonic way to write long if statement in list comprehension
I'm beginner in python and hope you help me find way to write if
statement correctly.我是 python 的初学者,希望您能帮助我找到正确编写if
语句的方法。 This is code i have:这是我的代码:
target_dir = Path(__file__).resolve().parents[1]
nav_files = [
x
for x in target_dir.rglob('conf.yaml')
if '.'.join(str(x.parent).replace(str(target_dir), '').lstrip('/').split('/')[:2]) in settings.MODULES
]
You may see unacceptably long if
statement.您可能会看到长得无法接受的if
语句。 As i understand there are 2 ways to resolve this:据我了解,有两种方法可以解决此问题:
nav_files
preparation and use some for
blocks单独nav_files
准备并将一些for
块if
statement by linebreaks(if it's possible)用换行符分隔if
语句(如果可能的话)What is the best practice?最佳做法是什么? Thanks!谢谢!
You can use a backslash before each newline to combine several physical lines as one logical line.您可以在每个换行符之前使用反斜杠将多个物理行组合为一个逻辑行。 A more common practice in Python is to wrap lines inside parentheses; Python 中更常见的做法是在括号内换行; then Python knows the statement has ho continue, and you don't need a backslash.然后 Python 知道语句有 ho 继续,你不需要反斜杠。
nav_files = [
x for x in target_dir.rglob('conf.yaml')
if '.'.join(
str(x.parent).replace(
str(target_dir), '').lstrip(
'/').split('/')[:2]) in settings.MODULES
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.