[Tutor] design question -- nested loops considered harmful?

Chad Crabtree flaxeater at yahoo.com
Tue Nov 30 03:46:59 CET 2004


Brian van den Broek wrote:

> This got me thinking about general design issues. In various
programs 
> I  have made much use of nested loops in order to parse data files.

> I've done this in cases where I am interested in pulling out some
data 
> which is identified by a delimiter. Below is a minimal example of
the 
> sort of thing I have been doing:
>
> date_flag = '[Date]'
> email_flag = '[Email]'
> item_flags = [date_flag, email_flag]
>
> def parse_file(list_of_lines):
>     data_dict = {}
>     for line in list_of_lines:
>         for item in item_flags:
>             if line.startswith(item):
>                 data_dict[item] = line[len(item):]
>                 break
>     return data_dict

Well After pondering this for about five minutes I cannot really see 
anything particularly in elegant about this.  Perhaps the only 
refinement that I have picked up recently is internal functions.  
Perhaps this would be more readable without cluttering your name
space.

def pars_file(list_of_lines):
####internal FunctionS###########
    def check_flags(line,flags=item_flags,adict=data_dict):
       for item in flags:
          if line.startswith(item):
             adict[item]=line[len(item)]
             return
####end internal functions####
####start main function suite####
    data_dict={}
    for line in list_of_lines:
       check_flags(line)
    return data_dict

Granted this adds a layer of indirection, but for more complex
examples 
I find this helpful when I need to look at this later, because it
hides 
some of the nesting.

Just My two cents.
      


	
		
__________________________________ 
Do you Yahoo!? 
Yahoo! Mail - You care about security. So do we. 
http://promotions.yahoo.com/new_mail


More information about the Tutor mailing list