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

Blake Winton bwinton at latte.ca
Tue Nov 30 14:56:47 CET 2004


Alan Gauld wrote:
> No, a loop over two items is not likely to be a major concern,
> but equally a simple if test might be more appropriate. And
> recall that you can often use boolean operators to eliminate
> multiple tests:
> 
> item_flags = [date_flag, email_flag]
>      ...
>      for line in list_of_lines:
>          if line.startswith(date_flag) or line.startswith(email_flag):
>                  doSomething()
>                  break

Of course, that only handles the case of testing for two flags.
For a more general case (and because I wanted to play around with reduce 
a little), I give you the following:
import operator
prefixes = ["aaa", "bbb"]
lines = ["abc","def","bbbdec", "ccc"]
for line in lines:
    print line, reduce( operator.or_,
                        [line.startswith(x) for x in prefixes] )
abc False
def False
bbbdec True
ccc False

or, more like your code:
for line in list_of_lines:
   if reduce( operator.or_, [line.startswith(flag) for flag in flags] ) :
     doSomething()
     break

(If anyone wants a description of what I'm doing there, please email me, 
and I'll be more than happy to describe it in more detail.)

Later,
Blake.



More information about the Tutor mailing list