python 中列表推导式或生成器表达式的行延续
你应该如何分解一个很长的列表理解?
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
我还在某个地方看到人们不喜欢使用 '\' 来分隔行, 但从来不明白为什么。这背后的原因是什么?
How are you supposed to break up a very long list comprehension?
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
I have also seen somewhere that people that dislike using '\' to break up lines,
but never understood why. What is the reason behind this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
工作正常,所以你几乎可以做你想做的事。我个人更喜欢
\
不太受欢迎的原因是它出现在一行的末尾,在那里它要么不突出,要么需要额外的填充,当行长度改变时必须修复:在这种情况下,使用括号:
works fine, so you can pretty much do as you please. I'd personally prefer
The reason why
\
isn't appreciated very much is that it appears at the end of a line, where it either doesn't stand out or needs extra padding, which has to be fixed when line lengths change:In such cases, use parens:
在处理多个数据结构的列表时,您还可以使用多个缩进。
请注意它如何使用 if 语句过滤到另一个列表。将 if 语句放到自己的行中也很有用。
You can also make use of multiple indentations in cases where you're dealing with a list of several data structures.
Notice how it also filters onto another list using an if statement. Dropping the if statement to its own line is useful as well.
我不反对:
在这种情况下你不需要
\
。一般来说,我认为人们会避免使用\
因为它有点难看,但如果它不是该行的最后一件事(确保后面没有空格),也会带来问题。不过,我认为为了缩短线路长度,使用它比不使用它要好得多。由于在上述情况下或者对于带括号的表达式来说
\
不是必需的,所以我实际上发现我什至很少需要使用它。I'm not opposed to:
You don't need
\
in this case. In general, I think people avoid\
because it's slightly ugly, but also can give problems if it's not the very last thing on the line (make sure no whitespace follows it). I think it's much better to use it than not, though, in order to keep your line lengths down.Since
\
isn't necessary in the above case, or for parenthesized expressions, I actually find it fairly rare that I even need to use it.我认为在这种情况下您不应该使用列表理解,而应使用
for
循环:在
for
循环上使用列表理解的一个原因 +.append()
的优点是它比使用显式的for
循环更加简洁。但是,当列表推导式需要拆分为多行时,这种简洁性可能会使表达式极难阅读。虽然 PEP8 没有明确禁止多行列表推导式,但 Google Python 风格指南 要求列表理解的每个部分都适合在一行上(强调我的):
I would argue that you shouldn't use a list comprehension in this case, and instead use a
for
loop:One reason to use list comprehensions over a
for
loop +.append()
is that it can be much more concise than using an explicitfor
loop. However, when the list comprehension needs to be split over multiple lines, that conciseness can make the expression extremely difficult to read.While PEP8 doesn't explicitly forbid multi-line list comprehensions, the Google Python Style Guide requires that each portion of a list comprehension fit on a single line (emphasis mine):