If I have this csv data: (I am using Python-3.4, by the way)
['20150101','2','1'] # row 0
['20150102','10','3'] # row 1
['20150103','4','2'] # row 2
['20150104','5','4'] # row 3
['20150105','12','6'] # row 4
....
And I want to:
- Multiply, say, (in pseudo-code) data[2] of row[1] (which is '3' in ['20150102','10','3']) with data[2] of row[0] (which is '1' in ['20150101','2','1']), and
- Iterate the calculation to continue on with (in pseudo-code) data[2] of row[2] * data[2] of row[1], data[2] of row[3] * data[2] of row[2], data[2] of row[4] * data[2] of row[3], and so on until data[2] of row[-1] * data[2] of row[-2],
How can I do the above?
What I have experimented with:
import csv
f = open('file.csv','r')
r = csv.reader(f)
for i, n in enumerate(r):
print(int(n[1])*int(n[2]))
...which only calculates data within the same row.
But what I need to do is to calculate data from row[i] with data from row[i-1] (i.e. data from previous row), and then iterate the calculation the entire file to row[-1] (last row).
Note: I don't want to import any module for this (except csv just for opening and reading the file). And if possible to write the code with as few lines as possible. Don't worry about where the result of the calculation will go or whether it will keep changing as the iteration progresses (it could be appended to a list or written to a separate csv file, etc, but that's not the problem at the moment).