Reputation: 194
Here is a description of what I want to do : I've 2 csv files. I want to search the same thing (lets call it "hugo") in my 2 files at the same time. The thing is that it only print one and not the other.
Here is my code :
try:
while True:
if pm10pl[j][2] == '"Victor Hugo"':
victor1 = pm10pl[j]
print victor1
if pm25pl[t][2] == '"Victor Hugo"':
victor2= pm25pl[t]
print victor2
j=j+1
t=t+1
except IndexError:
pass
I've tried different things such as elif instead of if, replace t by j, passing by 2 functions. Each if works perfectly when the other is not here, and when I invert the 2 of them, that's the same that print aka pm25pl.
Can't do anything.
(here is only the part of my code that has interest, opening of file etc works fine, the '""' is normal hugo appeared in my file as "hugo" (with the double quote))
Plus, I can't call victor1 and victor2 outside of the if.
Do you have any idea what's going on ?
Upvotes: 0
Views: 89
Reputation: 7903
Do one list comprehension for each csv file:
[pm10pl[i] for i in range(0,len(pm10pl)) if 'Victor Hugo' in pm10pl[i][2]]
[pm25pl[i] for i in range(0,len(pm25pl)) if 'Victor Hugo' in pm25pl[i][2]]
Upvotes: 0
Reputation: 2335
You can iterate through 2 lists simultaneously using itertool
's zip
function.
import itertools
l = []
for victor1, victor2 in itertools.izip_longest(pm10pl, pm25pl):
if victor1 and victor1[2] == '"Victor Hugo"':
#print victor1
if victor2 and victor2[2] == '"Victor Hugo"':
#print victor2
l.append((victor1, victor2)) # add the pair to list.
for i in l: # prints all pairs.
print i
Upvotes: 2