列表推导在某些情况下可能很有用,但它们也可能相当可怕阅读..作为一个有点夸张的例子,你会如何缩进以下内容?
allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
orestis.. 66
这取决于他们有多长.我倾向于像这样构造它们:
[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变得太长,它会被提升为一个函数.
这取决于他们有多长.我倾向于像这样构造它们:
[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变得太长,它会被提升为一个函数.
在我工作的地方,我们的编码指南会让我们做这样的事情:
all_posts_uuid_query = self.db.query(schema.allPostsUuid) all_posts_uuid_list = all_posts_uuid_query.execute(timeout=20) all_uuid_list = [ x.id for x in all_posts_uuid_list if ( x.type == "post" and not x.deleted # <-- if you don't care about NULLs / None ) ]
allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
对我来说太多了.也许这只是一个可怕的例子,因为"type"和"deleted"显然是db查询的一部分.
我倾向于认为如果列表理解跨越多行,那么它可能不应该是列表理解.话虽如此,我通常只是像其他人一样将这个东西拆分为"if"并在这里回答.