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

126

如何拆分一个非常长的列表推导式?

[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]

我也看到有人不喜欢使用“\”来换行,但我从未明白其中的原因。这背后的原因是什么?


3
可能是如何对Python列表理解进行缩进?的重复问题。 - Cristian Ciupitu
4个回答

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

58
具体来说,任何括号内的换行符都会被忽略,包括圆括号()、方括号[]和花括号{}。 - user395760

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


24

我不反对:

variable = [something_that_is_pretty_long
            for something_that_is_pretty_long
            in somethings_that_are_pretty_long]

在这种情况下,你不需要使用\。一般来说,人们避免使用\,因为它略显丑陋,而且如果它不是行末的最后一个字符,还可能会出现问题(请确保其后面没有空格)。但是,为了使行长度保持在合理范围内,使用它比不使用要好得多。

由于在上述情况或圆括号表达式中都不需要使用\,我实际上发现我甚至很少需要使用它。


0
我认为在这种情况下不应该使用列表推导式,而应该使用一个for循环:
result = []
for something_that_is_pretty_long in somethings_that_are_pretty_long:
    result.append(something_that_is_pretty_long)

使用列表推导式而不是for循环+.append()的一个原因是它比使用显式for循环更加简洁。然而,当列表推导式需要分成多行时,这种简洁性会使表达式变得极难阅读。
虽然PEP8并没有明确禁止多行列表推导式,但Google Python Style Guide要求列表推导式的每个部分都适合于一行(强调我的):

2.7 Comprehensions & Generator Expressions

对于简单情况可以使用。 每个部分必须适合一行:映射表达式、for子句、过滤器表达式。不允许使用多个for子句或过滤器表达式。当事情变得更加复杂时,请改用循环。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接