2017-04-11 93 views
1

我定義了一個函數來創建自定義假日日曆的商業日期範圍。我想我陷入了無限循環,但不知道爲什麼?自定義Python得到BDay範圍

import datetime as dt 

def get_bdate(start, end, hoildays): 
list = [] 
while start < end: 
    if start.weekday() >= 5: # sunday = 6; skipping weekends 
     continue 
    if start in holidays: # holidays is a custom set of dates 
     continue 
    list.append(start) 
    start += dt.timedelta(days=1) 
return list 

回答

1

你的問題是,如果它是一個工作日或假期,你不會增加循環的開始。通過使用continue,您最終會無限期地使用相同的起始值!

import datetime as dt 

def get_bdate(start, end, hoildays): 
    my_list = [] 
    while start < end: 
     if start.weekday() > 5 or start not in holidays: 
      my_list.append(start) 
     start += dt.timedelta(days=1) 
    return my_list 

更準確地使用前面的例子(儘管它重複start +=線:

import datetime as dt 

def get_bdate(start, end, hoildays): 
    my_list = [] 
    while start < end: 
     if start.weekday() >= 5: # sunday = 6; skipping weekends 
      start += dt.timedelta(days=1) 
      continue 
     if start in holidays: # holidays is a custom set of dates 
      start += dt.timedelta(days=1) 
      continue 
     my_list.append(start) 
     start += dt.timedelta(days=1) 
    return my_list 
+0

哦天吶只注意到史詩失敗 –

+0

請註明!。!正如接受,如果它幫助你:) –

+1

@ChristopherApple:使用'list'作爲變量名clobbers [內置類型](https://docs.python.org/2/library/stdtypes.html#sequence-types -str-Unicode的列表元組的ByteArray緩衝區-x範圍)。 –

1

documentation

continue語句是從C借來的,繼續循環的下一次迭代:

你需要改變你的代碼,以便start始終遞增:

import datetime as dt 

def get_bdate(start, end, holidays): 
    result = list() 
    while start < end: 
     if start.weekday() >= 5: # sunday = 6; skipping weekends 
      pass 
     elif start in holidays: # holidays is a custom set of dates 
      pass 
     else: 
      result.append(start) 
     start += dt.timedelta(days=1) 
    return result 

此外,請勿使用list作爲變量名稱,因爲您會剽竊built-in type

+0

感謝您的幫助,這是非常有用 –