python - python中列表推导或生成器表达式的续行

标签 python coding-style list-comprehension pep8

你应该如何分解一个很长的列表理解?

[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/

相关文章:

python - 计数器似乎没有正确添加

python - 使用列表理解生成的函数列表

python - 从 Python 列表中弹出所有项目

在 C 中编码 : efficiency of temporary local variables

haskell - Haskell 表达式中哪里允许换行?

c++ - astyle 没有缩进以 .或 ->

python - 从 python 中的一行中拉出特定的子字符串

python - 在 django rest framework searchfilter 中禁用多重搜索

python - 打印字符串以固定宽度和后缀左对齐

python - 将 matplotlib 颜色图转换为 seaborn 调色板