Python中列表推导或生成器表达式的换行续行

126 投票
4 回答
47689 浏览
提问于 2025-04-16 16:32

你应该怎么把一个很长的列表推导式拆分开呢?

[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]

我还听说过,有些人不喜欢用反斜杠('\')来换行,但我一直不明白为什么。这个背后有什么原因呢?

4 个回答

24

我并不反对:

variable = [something_that_is_pretty_long
            for something_that_is_pretty_long
            in somethings_that_are_pretty_long]

在这种情况下,你不需要用到\。一般来说,我觉得大家不喜欢用\,因为它看起来有点丑,而且如果它不是行尾的最后一个字符,可能会引发一些问题(确保后面没有空格)。不过,为了保持行的长度适中,我觉得用\还是比不用要好得多。

因为在上面的例子中,或者在带括号的表达式中,\并不是必须的,所以我发现自己其实很少需要用到它。

29

当你处理多个数据结构的列表时,你可以使用多层缩进来帮助组织代码。

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语句单独放在一行也是很有用的。

177
[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)

撰写回答