2016-07-26 73 views
0

用下面的代碼:追加數組爲一個循環的每個項目

class Calendar_Data(Resource): 
    def get(self): 
    result = [] 
    details_array = [] 
    # Times are converted to seconds 
    for day in life.days: 
     for span in day.spans: 
     if type(span.place) is str: 
      details = { 
      'name': span.place, 
      'date': 0, 
      'value': (span.length() * 60), 
      } 
      details_array.append(details) 
     data = { 
     'date': datetime.datetime.strptime(day.date, '%Y_%m_%d').strftime('%Y-%m-%d'), 
     'total': (day.somewhere() * 60), 
     'details': details_array 
     } 
     result.append(data) 
    return result 

我想要做的就是每天存在於天的列表,獲取了相應的跨度一天,並用details填充陣列。然後將該details傳遞給data陣列,以便在該列表中的每一天獲得該陣列。

這裏的問題是,當我使用上面的這些嵌套循環時,它使用所有天的所有跨度而不是每一天填充我details

我不瘦在這種情況下使用zip將工作。也許一些列表理解,但我仍然不完全理解。

示例輸入:

--2016_01_15 
@UTC 
0000-0915: home 
0924-0930: seixalinho station 
1000-1008: cais do sodre station 
1009-1024: cais do sodre station->saldanha station 
1025-1027: saldanha station 
1030-1743: INESC 
1746-1750: saldanha station 
1751-1815: saldanha station->cais do sodre station 
1815-1834: cais do sodre station {Waiting for the boat trip back. The boat was late} 
1920-2359: home [dinner] 

--2016_01_16 
0000-2136: home 
2147-2200: fabio's house 
2237-2258: bar [drinks] 

January的細節陣列的第十六應該有3項,但是每天不斷地示出了所有的所有天數的項目。

+0

您可以添加您的輸入示例,預期輸出和實際輸出。 – IanAuld

+0

@IanAuld我已經添加了它 –

回答

1

你在每個循環之間沒有重新聲明你的列表(Python有列表而不是數組)。您需要將創建的details_array移動到其中一個循環中,以便將其重新創建爲空。你可能會Wnt信號它看起來像這樣:

for day in life.days: 
    details_array = [] 
    for span in day.spans: 

這樣一個day的每個新的迭代你就會有一個新的空單。

相關問題