如何制作连续的字母列表python(从a-z然后从aa,ab,ac等) [英] How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)
问题描述
我想为类似于 Excel 工作表的应用程序制作一个按字母顺序排列的列表.
I would like to make a alphabetical list for an application similar to an excel worksheet.
用户将输入单元格数量,我想生成列表.例如,用户需要 54 个单元格.然后我会生成
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'
'a','b','c',...,'z','aa','ab','ac',...,'az', 'ba','bb'
我可以从 [ref] 生成列表>
I can generate the list from [ref]
from string import ascii_lowercase
L = list(ascii_lowercase)
我怎么把它拼接在一起?有人问了一个类似的 PHP 问题 此处.有人有 python 等价物吗?
How do i stitch it together? A similar question for PHP has been asked here. Does some one have the python equivalent?
推荐答案
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
结果:
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.
额外的样式提示:如果您不喜欢在底部循环中有显式的 break
,您可以使用 islice
使循环自行终止:
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
这篇关于如何制作连续的字母列表python(从a-z然后从aa,ab,ac等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!