NEWBIE: map | zip | list comp

engsolnom at ipns.com engsolnom at ipns.com
Fri Jan 2 06:23:00 CET 2004


Hello again...hope everyone had a great New Year...:)

In the quest to learn more about Python, I decided to create an arbitrary sequence,
then march each member through a 'field' of each of the members in turn, and just to complicate it a
bit, make the length of the field user defined.
Hard to explain...an example might serve:

10000
01000
00100
  .
  .
00009
01111
10111
11011
  .
  .
21111
12111
11211
and so forth.

The only coding I could come up with is:

base_seq = 'ABCD'
length = 6

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?

Thanks......Norm





More information about the Python-list mailing list