你应该如何打破一个很长的列表理解呢?
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
我也看到有些人不喜欢用'\‘来分隔行,但从来不知道为什么。这背后的原因是什么?
发布于 2012-02-18 05:41:41
在处理多个数据结构的列表时,也可以使用多个缩进。
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语句放在它自己的行中也很有用。
发布于 2011-04-28 02:58:16
我不反对:
variable = [something_that_is_pretty_long
for something_that_is_pretty_long
in somethings_that_are_pretty_long]
在这种情况下,您不需要\
。一般来说,我认为人们避免使用\
是因为它有点难看,但如果它不是最后一件事,也会带来问题(确保后面没有空格)。不过,我认为使用它要比不使用它好得多,这样可以减少您的代码行长度。
因为在上面的例子中\
不是必需的,或者对于带括号的表达式,我实际上发现我甚至很少需要使用它。
https://stackoverflow.com/questions/5809059
复制相似问题