列表推导式在某些情况下可能很有用,但读起来也可能相当糟糕。作为一个稍微夸张的例子,您将如何缩进以下内容?
allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
这取决于它们有多长。我倾向于这样构造它们:
[x.id for x
in self.db.query(schema.allPostsUuid).execute(timeout=20)
if x.type == 'post'
and x.deleted is not False
and ...
and ...]
这样每个表达式都有自己的行。
如果任何行变得太大,我喜欢将其提取到 lambda 或表达式中:
transform = lambda x: x.id
results = self.db.query(schema.allPostsUuid).execute(timeout=20)
condition = lambda x: x.deleted is not False and ... and ...
[transform(x) for x in results if condition(x)]
然后,如果 lambda 变得太长,它就会被提升为函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)