如何制作连续的字母列表python(从a-z然后从aa,ab,ac等) [英] How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)

查看:84
本文介绍了如何制作连续的字母列表python(从a-z然后从aa,ab,ac等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为类似于 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?

推荐答案

使用 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

结果:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆