我目前正在尝试用python写入CSV文件,但我只想每60次迭代打印一次'CurrentInv'。例如
outfile = open("Pension.csv", 'w')
for k in range(1,Iterations+1):
outfile.write(str( str(k) + ','))
outfile.write(str(CurrentInv[k][0])+',')
outfile.write(str(CurrentInv[k][60])+',')
outfile.write(str(CurrentInv[k][120])+',')
outfile.write(str(CurrentInv[k][180])+',')
outfile.write(str(CurrentInv[k][240])+',')
outfile.write(str(CurrentInv[k][300])+',')
outfile.write(str(CurrentInv[k][360])+',')
outfile.write(str('\n'))
outfile.close()
但我想在一个循环中获得这个。我试过了
outfile = open("Pension5.csv", 'w')
for k in range(1,Iterations+1):
outfile.write(str( str(k) + ','))
for i in range(0,Months+1):
outfile.write(str(CurrentInv[k][i])+',')
i=i+60
outfile.write(str('\n'))
outfile.close()`
但是,这仍然会将CurrentInv的所有值从0打印到几个月而不是每60次迭代。任何帮助将不胜感激!
答案 0 :(得分:1)
尝试以下方法:
with open("Pension5.csv", 'w') as outfile:
for k in range(1, Iterations+1):
outfile.write(str(str(k) + ','))
for i in range(0, Months+1, 60):
outfile.write(str(CurrentInv[k][i]) + ',')
outfile.write(str('\n'))
它为范围指定了60的步长,以便每次迭代添加60而不是1.在示例情况下,月份应为360。如果您希望Months为6而不是360,请检查以下内容:
with open("Pension5.csv", 'w') as outfile:
for k in range(1, Iterations+1):
outfile.write(str(str(k) + ','))
for i in range(0, Months+1):
outfile.write(str(CurrentInv[k][i*60]) + ',')
outfile.write(str('\n'))