111

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

[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]

我还在某处看到人们不喜欢使用“\”来分行,但不明白为什么。这背后的原因是什么?

4

3 回答 3

160
[x
 for
 x
 in
 (1,2,3)
]

工作正常,所以你几乎可以随心所欲。我个人更喜欢

 [something_that_is_pretty_long
  for something_that_is_pretty_long
  in somethings_that_are_pretty_long]

之所以不受欢迎的原因\是它出现在一行的末尾,在那里它要么不突出,要么需要额外的填充,当行长改变时必须修复它:

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)
于 2011-04-27T18:56:41.197 回答
25

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

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
    ]
]

请注意它如何使用 if 语句过滤到另一个列表。将 if 语句放到它自己的行中也很有用。

于 2012-02-17T21:41:41.483 回答
24

我不反对:

variable = [something_that_is_pretty_long
            for something_that_is_pretty_long
            in somethings_that_are_pretty_long]

\在这种情况下你不需要。一般来说,我认为人们避免\使用它是因为它有点难看,但如果它不是最后一行(确保后面没有空格),也会出现问题。不过,我认为使用它比不使用它要好得多,以保持你的线路长度。

由于\在上述情况下或括号表达式中没有必要,我实际上发现我什至很少需要使用它。

于 2011-04-27T18:58:15.543 回答