2011-09-01 20 views
0

我真的很喜歡將我的代碼縮減爲儘可能少的行。我有下面的代碼,我一直試圖把它放在一行,如果任何人可以建議,我將不勝感激。我如何將循環迭代器轉換爲整齊pythonic一行循環

 list_choices = {} 
     if_changed = '' 
     for i in obj: 
      if if_changed!=i.area.region.id: 
       if_changed = i.area.region.id 
       list_choices.setdefault(if_changed, []) 

      list_choices[if_changed].append([i.id, i.name]) 
+5

很難幫助時,你不說明你正在試圖做或得到期望的輸出是什麼。 –

+0

因爲你的循環是有狀態的,所以我能想出的任何東西都比原來更難閱讀,並且可能更長。 – wberry

+1

在這裏介紹的代碼中,監控'i.area.region.id'發生變化是沒有必要的。如果是這樣,可以使用'itertools.groupby'而不是這種技術。 –

回答

4
list_choices = {} 
for i in obj: 
    list_choices.setdefault(i.area.region.id, []).append([i.id, i.name]) 

,或者使用list_choices = collections.defaultdict(list)最後一行是:

list_choices[i.area.region.id].append([i.id, i.name]) 
0

不是很清楚你想做的事,所以我猜你想組的東西由他們的OBJ area.region.id然後將它們添加到字典:

import itertools 

list_choices = {} 
obj_by_region = itertools.groupby(obj, key=lambda x: x.area.region.id) 
for region, elements in obj_by_region: 
    list_choices[region] = [[el.id, el.name] for el in elements]