你应该如何分解一个很长的列表理解?
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
我还曾在某处看到人们不喜欢使用“\”来分行, 但一直不明白为什么。这背后的原因是什么?
最佳答案
[x
for
x
in
(1,2,3)
]
工作正常,所以你可以随心所欲。我个人更喜欢
[something_that_is_pretty_long
for something_that_is_pretty_long
in somethings_that_are_pretty_long]
\
不受欢迎的原因是它出现在一行的 end 处,它要么不突出,要么需要额外的填充,当行长改变时必须固定:
x = very_long_term \
+ even_longer_term_than_the_previous \
+ a_third_term
在这种情况下,请使用括号:
x = (very_long_term
+ even_longer_term_than_the_previous
+ a_third_term)
关于python - python中列表推导或生成器表达式的续行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5809059/