python中列表理解或生成器表达式的行继续
你怎么能把一长串的理解力分解呢python中列表理解或生成器表达式的行继续,python,coding-style,list-comprehension,pep8,Python,Coding Style,List Comprehension,Pep8,你怎么能把一长串的理解力分解呢 [something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long] 我还看到过一些人不喜欢用“\”来打断台词, 但我始终不明白为什么。这背后的原因是什么 [x for x in (1,2,3) ] 很好,所以你可以随心所欲。我个人更喜欢 [something_that_is_pretty_long for some
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
我还看到过一些人不喜欢用“\”来打断台词,
但我始终不明白为什么。这背后的原因是什么
[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
在这种情况下,使用parens:
x = (very_long_term
+ even_longer_term_than_the_previous
+ a_third_term)
我不反对:
variable = [something_that_is_pretty_long
for something_that_is_pretty_long
in somethings_that_are_pretty_long]
在这种情况下,您不需要\
。一般来说,我认为人们避免使用\
,因为它有点难看,但如果不是最后一件事,也可能会出现问题(确保后面没有空格)。不过,我认为使用它比不使用要好得多,这样可以减少线路长度
由于
\
在上述情况下或括号表达式中是不必要的,我实际上发现我几乎不需要使用它。在处理多个数据结构列表的情况下,也可以使用多个缩进
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语句放到它自己的行中也很有用。特别是,在任何括号内都会忽略换行符-
()
,[]
和{}
。我特别喜欢这个答案,如图所示,断行的几个常规方面包括循环的嵌套列表理解。