2016-02-25 63 views
0

假设我有这样的代码:复杂的嵌套列表内涵,PEP8

questions = [{ 
    "title": q.title, 
    "votes": q.get_total_votes(), 
    "options": [{ 
     "title": o.title, 
     "votes": o.votes 
    } for o in q.get_options()] 
} for q in queue.get_questions()] 

但大多数PEP8例子说我应该写这样的:

questions = [{"title": q.title, 
       "votes": q.get_total_votes(), 
       "options": [{"title": o.title, "votes": o.votes} 
          for o in q.get_options()]} 
      for q in queue.get_questions()] 

是第二个版本preferrable /更具可读性?或者,也许列表内涵是不是要做到这一点的最好办法,我应该做纯

questions = [] 
for q in queue.get_questions(): 
    options = [] 
    for o in q.get_options(): 
     options.append({"title": o.title, "votes": o.votes}) 
    questions.append({"title": q.title, 
         "votes": q.get_total_votes(), 
         "options": options}) 

回答

0

的PEP8方式是最好的,不仅是可读的,而且在将来你可以很容易地修改它。第一种方式也是可读的,但不是很好,因为不是所有的按键都排列得很好,而且你必须选项卡嵌套你的选项键,再加上如果你使用较小的终端(如果你使用vim或任何终端编辑器)查看它,那么它会很烦人。尽管我的想法。

0

我会写这样的,我觉得是更具可读性:

questions = [{"title": q.title, 
       "votes": q.get_total_votes(), 
       "options": [{"title": o.title, "votes": o.votes} 
          for o in q.get_options()]} 
      for q in queue.get_questions()]