How to create a continuous python alphabetical list (from az, then from aa, ab, ac, etc.)

I would like to make an alphabetical list for an application similar to an excel worksheet.

The user enters the number of cells, and I would like to create a list. For example, a user needs 54 cells. Then I would generate

a, b, c, ...,

I can generate a list from [ref]

from string import ascii_lowercase L = list(ascii_lowercase) 

How to sew it together? A similar question for PHP was asked here . Does anyone have a python equivalent?

+10
source share
4 answers

Use itertools.product .

 from string import ascii_lowercase import itertools def iter_all_strings(): for size in itertools.count(1): for s in itertools.product(ascii_lowercase, repeat=size): yield "".join(s) for s in iter_all_strings(): print(s) if s == 'bb': break 

Result:

 a b c d e ... y z aa ab ac ... ay az ba bb 

This has the added benefit of going well beyond two-letter combinations. If you need a million lines, he will happily give you three, four and five letter lines.


Bonus style tip: if you don't like the explicit break inside the bottom loop, you can use islice to end the loop yourself:

 for s in itertools.islice(iter_all_strings(), 54): print s 
+24
source

You can use list comprehension.

 from string import ascii_lowercase L = list(ascii_lowercase) + [letter1+letter2 for letter1 in ascii_lowercase for letter2 in ascii_lowercase] 
+1
source

After @Kevin's answer:

 from string import ascii_lowercase import itertools # define the generator itself def iter_all_strings(): size = 1 while True: for s in itertools.product(ascii_lowercase, repeat=size): yield "".join(s) size +=1 

The code below allows you to generate strings that can be used, for example, to create unique shortcuts.

 # define the generator handler gen = iter_all_strings() def label_gen(): for s in gen: return s # call it whenever needed print label_gen() print label_gen() print label_gen() 
+1
source

I finished doing mine. I think this can create any number of letters.

 def AA(n, s): r = n % 26 r = r if r > 0 else 26 n = (n - r) / 26 s = chr(64 + r) + s if n > 26: s = AA(n, s) elif n > 0: s = chr(64 + n) + s return s 

n = quantity | r = remaining (26 letters AZ) | s = string

To print the list:

 def uprint(nc): for x in range(1, nc + 1): print AA(x,'').lower() 

Used by VBA before converting to python:

 Function AA(n, s) r = n Mod 26 r = IIf(r > 0, r, 26) n = (n - r) / 26 s = Chr(64 + r) & s If n > 26 Then s = AA(n, s) ElseIf n > 0 Then s = Chr(64 + n) & s End If AA = s End Function 
0
source

Source: https://habr.com/ru/post/984449/


All Articles