Search code examples
python-2.7python-2.xarcmap

How to create an alphanumeric grid in a certain sequence allowing double digit numbers?


I have a grid feature class that varies in size and shape. My test shapefile is a 3x4 grid. I need to create an alphanumeric sequence that goes in a specific order but can be scaled for a different size grid. Below is the order the grid is in:

A4 | B4 | C4
A3 | B3 | C3
A2 | B2 | C2
A1 | B1 | C1

and to use this alphanumeric sequence, the list will need to be printed in a specific order (starting from the bottom left of the table, moving to the right, and then returning to the left value on the next row up: A1, B1, C1, A2, B2, C2, A3, B3, C3, A4, B4, C4

I had this:

from itertools import product
from string import ascii_uppercase, digits

for x, y in product(ascii_uppercase, digits):
    print('{}{}'.format(x, y))

It generates a sequence like: A0 through A9, then B0 through B9, and so forth. However I also need larger grids so the script would have to compensate and allow the sequence to use double digits after 9 if the grid is larger than 9 high. ie. A10, B10, C10

I then tried to make 2 lists and then combine them together, but I ran into the problem of joining these in the sequence I need.

w = 3
h = 4

alpha = []
numeric = []
for letter in ascii_uppercase[:w]:
    alpha.append(letter)

for num in range(1, h+1):
    numeric.append(num)

I assume I might not need to make a numeric list, but don't know how to do it. I know slightly more than just the basics of python and have created so more complex scripts, but this is really puzzling for me! I feel like I am so close but missing something really simple from both of my samples above. Thank you for any help you can give me!

Solved, here is what I have for others who might need to use my question:

w = 9
h = 20

alpha = []
numeric = []
for letter in ascii_uppercase[:w]:
    alpha.append(letter)

for num in range(1, h+1):
    numeric.append(num)

longest_num = len(str(max(numeric)))
for y in numeric:
    for x in alpha:
        print '{}{:0{}}'.format(x, y, longest_num)

I didn't need the code formatted as a table since I was going to perform a field calculation in ArcMap.


Solution

  • After you compute numeric, also do:

    longest_num = len(str(max(numeric)))
    

    and change your format statement to:

    '{}{:0{}}'.format(x, y, longest_num)
    

    This ensures that when you get to double digits you get the following result:

    A12 | B12 | C12
    A11 | B11 | C11
    ...
    A02 | B02 | C02
    A01 | B01 | C01
    

    To actually print the grid however you need to change your code:

    longest_num = len(str(max(numeric)))
    for y in reversed(numeric):
        print(" | ".join('{}{:0{}}'.format(x, y, longest_num)
                         for x in alpha))