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

sas*_*ker 98 python coding-style list-comprehension pep8

你怎么打破一个很长的列表理解?

[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
Run Code Online (Sandbox Code Playgroud)

我也看到过某些人不喜欢使用'\'来分解线条,但却从不理解为什么.这背后的原因是什么?

Fre*_*Foo 139

[x
 for
 x
 in
 (1,2,3)
]
Run Code Online (Sandbox Code Playgroud)

工作正常,所以你可以随心所欲地做.我个人更喜欢

 [something_that_is_pretty_long
  for something_that_is_pretty_long
  in somethings_that_are_pretty_long]
Run Code Online (Sandbox Code Playgroud)

之所以\不被理解的原因是它出现在一行的末尾,它不会突出或需要额外的填充,必须在行长度改变时修复:

x = very_long_term                     \
  + even_longer_term_than_the_previous \
  + a_third_term
Run Code Online (Sandbox Code Playgroud)

在这种情况下,使用parens:

x = (very_long_term
     + even_longer_term_than_the_previous
     + a_third_term)
Run Code Online (Sandbox Code Playgroud)

  • 具体来说,在*any*括号 - `()`,`[]`和`{}`中忽略换行符. (44认同)

Dan*_*een 22

我不反对:

variable = [something_that_is_pretty_long
            for something_that_is_pretty_long
            in somethings_that_are_pretty_long]
Run Code Online (Sandbox Code Playgroud)

\在这种情况下你不需要.一般来说,我认为人们会避免\因为它有点丑陋,但如果它不是最后的东西也会产生问题(确保没有空格跟随它).我认为使用它比使用它要好得多,以便保持线路长度.

由于\在上述情况下不是必需的,或者对于带括号的表达式,我实际上发现我甚至需要使用它是相当罕见的.


MrO*_*les 19

在处理多个数据结构列表的情况下,您还可以使用多个缩进.

new_list = [
    {
        'attribute 1': a_very_long_item.attribute1,
        'attribute 2': a_very_long_item.attribute2,
        'list_attribute': [
            {
                'dict_key_1': attribute_item.attribute2,
                'dict_key_2': attribute_item.attribute2
            }
            for attribute_item
            in a_very_long_item.list_of_items
         ]
    }
    for a_very_long_item
    in a_very_long_list
    if a_very_long_item not in [some_other_long_item
        for some_other_long_item 
        in some_other_long_list
    ]
]
Run Code Online (Sandbox Code Playgroud)

注意它如何使用if语句过滤到另一个列表.将if语句删除到自己的行也很有用.

  • 我特别喜欢这个答案,因为它显示了“for”循环的换行_包括_嵌套列表理解的几个传统方面。 (2认同)