3 回答
TA贡献1772条经验 获得超5个赞
这里不需要递归:
from itertools import product
years = [2017, 2018]
months = [1, 2, 3]
for year, month in product(years, months):
print(f'year: {year} month: {month}')
因为 Python 缺乏尾递归优化并且调用用户定义函数的成本相对较高,所以递归只应在比循环更清晰的情况下使用。
TA贡献1805条经验 获得超9个赞
是这样的:
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()
我建议您重构此代码并使用循环而不是递归。
TA贡献1906条经验 获得超3个赞
我试着在递归函数上做一些 OOP 来找点乐子。这是我解决它的方法,希望你能觉得它有用。基本上解决它需要在第一个条件中添加一个小于或等于,当它完成时,为了避免 IndexError,我使用了一个 catch,因为它是预期行为的一部分。
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()
添加回答
举报