3 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
這里不需要遞歸:
from itertools import product
years = [2017, 2018]
months = [1, 2, 3]
for year, month in product(years, months):
print(f'year: {year} month: {month}')
因?yàn)?Python 缺乏尾遞歸優(yōu)化并且調(diào)用用戶定義函數(shù)的成本相對(duì)較高,所以遞歸只應(yīng)在比循環(huán)更清晰的情況下使用。

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
是這樣的:
years = [2017, 2018]
years_index = 0
month = 1
def parse():
global years
global years_index
global month
print(str('year: ' + str(years[years_index])) + ' month: ' + str(month))
if month < 3:
month +=1
parse()
else:
years_index +=1
month = 1
if years_index >= len(years):
return
parse()
parse()
我建議您重構(gòu)此代碼并使用循環(huán)而不是遞歸。

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
我試著在遞歸函數(shù)上做一些 OOP 來(lái)找點(diǎn)樂(lè)子。這是我解決它的方法,希望你能覺(jué)得它有用。基本上解決它需要在第一個(gè)條件中添加一個(gè)小于或等于,當(dāng)它完成時(shí),為了避免 IndexError,我使用了一個(gè) catch,因?yàn)樗穷A(yù)期行為的一部分。
class Example(object):
#Define variables on an object level
def __init__(self):
self.years = [2017, 2018]
self.years_index = 0
self.month = 1
def parse(self):
try:
print(str('year: ' + str(self.years[self.years_index])) + ' month: ' + str(self.month))
#Had to add an equal sign to make it work on the next year, otherwise it would stop here.
if self.years_index <= len(self.years) -1:
if self.month < 3:
self.month +=1
else:
self.years_index +=1
self.month = 1
self.parse()
pass
#The catch block is used when the index gets higher than the list's length. So that it does not
#cause an error, because it is the intended behavior for me.
except Exception as e:
print('Ran out of years');
#Calling function
example = Example()
example.parse()
添加回答
舉報(bào)