[Tutor] Problem with nested for-in

spir denis.spir at free.fr
Thu Jan 29 16:29:05 CET 2009


Le Thu, 29 Jan 2009 11:06:57 +0000,
"emmanuel.delaborde" <emmanuel.delaborde at cimex.com> a écrit :

> Hello,
> 
> I have the following snippet :
> 
> lines = csv.reader(open("CATEGORY.csv","r"))
> lines2 = csv.reader(open("CATEGORYLIST.csv","r"))
> 
> old_cats = []
> for line in lines:
>      stories = []
>      for line2 in lines2:
>          if line2[1] == line[0]:
>              stories.append(line2[0])
>      old_cats.append((line[0],line[2], stories))
> 
> 
> what happens is that
> 
> for the first elt of lines, the nested for in runs fine
> but then never seem to run again while the top level loop iterates  
> through the rest of lines
> 
> consequently stories accumulate nothing...
> 
> Can someone explain please ?
> 
> Thanks
> 
> E

I rewrote you nested loop only to have it clearer to my eyes:

for line in lines:
    word0 = line[0]
    stories = [line2[0] for line2 in lines2 if line2[1] == word0]
    old_cats.append((line[0],line[2], stories))
(word0 is here only to avoid computing it for each line2)

Only a guess: if ever cvs.reader returns an iterator, instead of a list, then once it has reached last line it is "like empty" (raises StopIterator). So that the internal loop can be walked thru only once -- like if lines2 was empty.
To check that, simply to outputing twice all items in lines1 or lines 2. Or output lines2's type.
If this is the issue, remedies can be:
* rebuild lines2 for each iteration inside the outer loop
* cast lines2 into a list
(I don't have any csv file to test)

Denis

------
la vida e estranya


More information about the Tutor mailing list