Nested loop
Steve Holden
steve at holdenweb.com
Wed Nov 30 05:33:08 EST 2005
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 result of the readlines() function *is* a list, which is precisely
why it's been used up:
>>> f = file("mail.py")
>>> type(f.readlines())
<type 'list'>
>>>
A second call to readlines just gets an empty list, since there are no
more lines left to be read.
> Either turn it into a list(so you can reuse it) or better yet, turn it
> into a dict which would speed up the matching process. Either way, it
> better be done outside of the outer loop.
>
The solution, as already proposed, is to bind the list of lines to a
nanme so it can be reused.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list