0

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:

  1. 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
  2. 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).

Dorky
  • 111
  • 1
  • 3
  • 10
  • Why does nobody know how to solve this? – Dorky Jan 28 '15 at 15:16
  • Why don't you *"want to import any module for this"*? If you use [`itertools`](https://docs.python.org/2/library/itertools.html), which is also part of the standard library and is designed for exactly these kinds of tasks (working memory-efficiently with iterable objects), it will become very easy. – jonrsharpe Feb 07 '15 at 09:14
  • possible duplicate of [Iterate a list as pair (current, next) in Python](http://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python) – jonrsharpe Feb 07 '15 at 09:31

1 Answers1

0

You will have to create a Python list in a variable, and then loop over the rows while appending the column's data to the list. After looping, loop over the list to perform the calculation.

For example if you wanted to multiply all the numbers in column 2 of each row:

import csv
f = open('file.csv','r')
r = csv.reader(f)
myData = []
for i, n in enumerate(r):
    myData.append(int(n[1])
product = 1
for num in myData:
    product *= num
Al Sweigart
  • 11,566
  • 10
  • 64
  • 92