如何缩进 Python 列表理解?

新手上路,请多包涵

列表推导式在某些情况下可能很有用,但它们读起来也可能相当糟糕。作为一个稍微夸张的例子,您将如何缩进以下内容?

 allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]

原文由 dbr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 491
2 个回答

这取决于它们有多长。我倾向于像这样构造它们:

 [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 变得太长,它就会被提升为一个函数。

原文由 orestis 发布,翻译遵循 CC BY-SA 2.5 许可协议

在我工作的地方,我们的编码指南会让我们做这样的事情:

 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
    )
]

原文由 guzzloid 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏