如何缩进Python列表推导? [英] How to indent Python list-comprehensions?
本文介绍了如何缩进Python列表推导?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
列表推导在某些情况下可能很有用,但是它们也可能相当可怕。作为一个稍微夸张的例子,你将如何缩进以下内容?
List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?
allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
推荐答案
我倾向于这样构造它们:
It depends on how long they are. I tend to structure them like so:
[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 ...]
这样每个表达式都有自己的行。
That way every expression has its own line.
如果任何行变得太大,我喜欢在lambda或表达式中提取它:
If any line becomes too big I like to extract it out in a lambda or expression:
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变得太长,它会被提升为一个函数。
And then if a lambda becomes too long it gets promoted to a function.
这篇关于如何缩进Python列表推导?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文