Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

enumerate - How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)

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

A user would input number of cells and I would like to generate list. For example a user needs 54 cells. Then I would generate

'a','b','c',...,'z','aa','ab','ac',...,'az', 'ba','bb'

I can generate the list from [ref]

 from string import ascii_lowercase
 L = list(ascii_lowercase) 

How do i stitch it together? A similar question for PHP has been asked here. Does some one have the python equivalent?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 strings, it will happily give you three and four and five letter strings.


Bonus style tip: if you don't like having an explicit break inside the bottom loop, you can use islice to make the loop terminate on its own:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...