NEWBIE: map | zip | list comp

sdd daniels at dsl-only.net
Fri Jan 2 07:01:12 CET 2004


engsolnom at ipns.com wrote:

> ...
> 
> for char_1 in base_seq:         # Loop thru the set char_1 at a time
>     for char_2 in base_seq:     # Loop thru the seq again for each char_1
>         if char_2 == char_1: continue # Don't march 'A' thru a field of 'A's
>         for ix in range(length):                     # Now march char_2 thru a field of char_1's
>             print (char_1 * length)[:ix] + char_2 + (char_1 * length)[ix:-1]

> which, as you can see, has three nested FOR loops. I played with map, zip and list comps a bit, but
> couldn't figure out how to compress the above code. Am I barking up the wrong Python tree?

I'd think so.  The 3-level nest looks fine (clear) to me.
The things I might change about the above code:

     for char_1 in base_seq:
         copies = char_1 * (length-1)
         for char_2 in base_seq:
             if char_2 != char_1:
                 # For every pair of non-matching characters
                 for ix in range(length):
                     # March char_2 thru a field of char_1's
                     print copies[:ix] + char_2 + copies[ix:]

or:

     for char_1 in base_seq:
         for char_2 in base_seq:
             if char_2 != char_1:
                 # For every pair of non-matching characters
                 for ix in range(length):
                     # March char_2 thru a field of char_1's
                     print char_1 * ix + char_2 + char_1 * (length-1-ix)

The point is to go for clarity, not brevity.  I'd think about
better names than char_1 and char_2, however.


-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list