Python 中每 N 次迭代的特定语句
Specific statement every N iterations in Python
我想创建一个循环,每 12 个月,'year' 变量应该递增 1,直到达到限制。我一个人做不到。这是我试过的(在这种情况下,结局应该是2013年):
years=[]
begin= 2010
for i in range(0,40):
year= begin
if ((i % 12 == 0) and (i != 0)):
year+=1
years.append(year)
else:
years.append(year)
years
我得到的唯一结果是:[2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2011, 2010, 2010...]
非常感谢您的帮助!
这是你可以做的:
我假设范围被认为是这里的月数。
years = [] # store the years from begin
begin = 2010
count_years = -1
for i in range(0,40,12): # each 12 months a year - step 12
count_years +=1 # add one year after each increment
end = begin + count_years # find the end year until last increment
years.append(end) # append to the list.
print(years)
打印年份会得到:
[2010, 2011, 2012, 2013]
希望这是你需要的。
我想创建一个循环,每 12 个月,'year' 变量应该递增 1,直到达到限制。我一个人做不到。这是我试过的(在这种情况下,结局应该是2013年):
years=[]
begin= 2010
for i in range(0,40):
year= begin
if ((i % 12 == 0) and (i != 0)):
year+=1
years.append(year)
else:
years.append(year)
years
我得到的唯一结果是:[2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2011, 2010, 2010...]
非常感谢您的帮助!
这是你可以做的:
我假设范围被认为是这里的月数。
years = [] # store the years from begin
begin = 2010
count_years = -1
for i in range(0,40,12): # each 12 months a year - step 12
count_years +=1 # add one year after each increment
end = begin + count_years # find the end year until last increment
years.append(end) # append to the list.
print(years)
打印年份会得到:
[2010, 2011, 2012, 2013]
希望这是你需要的。