2014-01-24 36 views
0

我无法在PEP 8样式指南中找到答案。 是否有可能通过使用圆括号而不是反斜杠来分解长的for语句?分手冗长的语句

下将导致语法错误:

for (one, two, three, four, five in 
    one_to_five): 
    pass 

回答

2

如果长的部分是拆包,我只想避免它:

for parts in iterable: 
    one, two, three, four, five, six, seven, eight = parts 

,或者如果它真的很长:

for parts in iterable: 
    (one, two, three, four, 
    five, six, seven, eight) = parts 

如果iterable是一个长期的表现,你应该把它在一条线本身之前循环:

iterable = the_really_long_expression(
       eventually_splitted, 
       on_multiple_lines) 
for one, two, three in iterable: 

如果很长,那么你可以结合这些约定。

+0

我觉得这个答案更具可读性。 –

3

是的,你可以在in关键字后用括号:

for (one, two, three, four, five) in (
        one_to_five): 
    pass 

在你的问题,因为贴了,你不小心掉落开幕括号,这会导致您收到的语法错误。