Nested loop

Bengt Richter bokr at oz.net
Wed Nov 30 17:41:26 EST 2005


On 30 Nov 2005 00:37:43 -0800, 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.
>
>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.
>
Yes, and unless there is an ordering requirement that can't be ignored or achieved
by sorting afterwards, symbols seems like it could be a set. E.g., (untested)

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

It would probably be more robust to check for blank lines and showme missing fields
and symbol duplicates also.

Regards,
Bengt Richter



More information about the Python-list mailing list