-1

How to Generate alphabetic list of given length in lexical order same as column header in MS excel.

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE' . . . ]

If length of list is given 28 then ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z', 'AA', 'AB']

If length of list is given 35 then ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI']

3 Answers3

2

You could try this list comprehension:

>>> import string
>>> x = 35
>>> [string.ascii_uppercase[i] if i < 26 else string.ascii_uppercase[i // 26 - 1] + string.ascii_uppercase[i % 26] for i in range(x)]
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI']
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 1
    OP doesn't say the upper limit for these is two characters; they say "given length"... – AKX Sep 08 '21 at 06:52
  • 1
    this code is wrong and don't work for input x > 26*26 and your code didn't work for 'AAA' or 'BBB' or 'AAAA' or ... this hasty solution – I'mahdi Sep 08 '21 at 06:57
1

Maybe the following would work:

from openpyxl.utils.cell import get_column_letter
x = 35
lst = [get_column_letter(i + 1) for i in range(x)]
print(lst)

Prints:

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI']
JvdV
  • 70,606
  • 8
  • 39
  • 70
1

Using itertools.product with all the letters gives you the combinations you want:

>>> list(product(ascii_uppercase, repeat=3))
[('A', 'A', 'A'),
 ('A', 'A', 'B'),
 ('A', 'A', 'C'),
 ('A', 'A', 'D'),
 ('A', 'A', 'E'),
 ('A', 'A', 'F'),
 ...
 ('Z', 'Z', 'Z')]

We need to modify the repeat if we're out items for a given repeat. Making it a generator:

from string import ascii_uppercase

def gen_columns():
    n = 1
    while True:
        # yield the items
        yield from [''.join(group) for group in product(ascii_uppercase, repeat=n)]
        # we're out of all combinations, add one more letter.
        n += 1

To take arbitrary number of elements from this generator, use itertools.islice:

>>> list(islice(gen_columns(), 35))
['A',
 'B',
 'C',
 'D',
 'E',
 'F',
 'G',
 'H',
 'I',
 'J',
 'K',
 'L',
 'M',
 'N',
 'O',
 'P',
 'Q',
 'R',
 'S',
 'T',
 'U',
 'V',
 'W',
 'X',
 'Y',
 'Z',
 'AA',
 'AB',
 'AC',
 'AD',
 'AE',
 'AF',
 'AG',
 'AH',
 'AI']

Credit: Repeating letters like excel columns?

Péter Leéh
  • 2,069
  • 2
  • 10
  • 23