Nested loop

Scott David Daniels scott.daniels at acm.org
Wed Nov 30 17:02:30 CET 2005


Steve Holden wrote:
> bonono at gmail.com wrote:
>> viewcharts wrote:
>>
>>> I am reading two text files comparing the values in one to the other,
>>> this requires two loops. The problem is that when the inner loop is
>>> finished, it never goes back into the loop. Any suggestions?
>>>
>>> for refSymbol in symbols.readlines():
>>>    for lookupSymbol in myfile.readlines():
>>>        showme = lookupSymbol.split('\t')
>>>        if showme[3] == refSymbol.strip():
>>>            priceNew.write(refSymbol.strip()+" "+showme[10])
>>
>> As another poster said, you have "used up" the inner iterable in the
>> first round, it is an iterable, just not like a list where you can use
>> multiple times.
...
 > The solution, as already proposed, is to bind the list of lines to a
> nanme so it can be reused.
> 
> regards
>  Steve

Or you could read each on the fly, and rewind the inner:

     for refSymbol in symbols:
        for lookupSymbol in myfile:
            showme = lookupSymbol.split('\t')
            if showme[3] == refSymbol.strip():
                priceNew.write(refSymbol.strip() + " " + showme[10])
        myfile.seek(0)

This is probably more what you wanted, but Steve's suggestion will run
much faster.

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list