Simple problem not sure what's wrong but: I am trying to iterate through two lists which were read from a csv file as follows:
for row1 in (list(csv_data1)):
for row2 in (list(csv_data2)):
# do something with row2 and row2
However after each iteration of the outer for loop, the inner for loop does not recognize that the outer for loop is iterated! For example if I do this:
for row1 in (list(csv_data1)):
for row2 in (list(csv_data2)):
# do something with row2 and row2
print row1
The elements of row1 get printed properly. However if I try to print the element of the outermost loop within the inner loop like so:
for row1 in (list(csv_data1)):
for row2 in (list(csv_data2)):
# do something with row2 and row2
print row1
I only get the first row of (list(csv_data1)) multiple times!
So if csv_data1 = [['a','b'],['b','c']] for example, I expect the above print statement (print in inner loop) to print:
[['a','b']
# repeated prints of above for however long csv_data2 is ...
['b','c']]
# repeated prints of above for however long csv_data2 is ...
But instead I get the following:
[['a','b']
# repeated prints of above for however long csv_data2 is ...
['a','b']]
# repeated prints of above for however long csv_data2 is ...
I.e. I can't get both loops to iterate through each other. I'm missing something very obvious, any help will be greatly appreciated. Thanks.
Edit: More specifically here is what I am trying to do: (I'm just printing right now to try to diagnose the problem)
f1 = open('file1.csv', 'rU')
f2 = open('file2.csv', 'rU')
reader1 = csv.DictReader(f1)
reader2 = csv.DictReader(f2)
# Grab desired columns from csv file
cols_desired = 'district,blockname,villagename'.split(',')
desired_cols_1 = (list(row[col]) for col in cols_desired) for row in reader1)
desired_cols_2 = (list(row[col]) for col in cols_desired) for row in reader2)
for row1 in (list(desired_cols_1)):
for row2 in (list(desired_cols_2)):
print row1
# XXX this prints only the first row of list(desired_cols_1) repeated times for some reason!