python - 创建按字母顺序升序的列表

标签 python alphabetical

我想创建按字母顺序升序排列的名称,例如 Excel 中的列名。那就是我想要……像 a,b,c,...,z,aa,ab,...az,...zz,aaa,aab,....

我试过:

for i in range(1000):
    mod = int(i%26)
    div = int(i/26)
    print(string.ascii_lowercase[div]+string.ascii_lowercase[mod])

zz 之前有效,但由于索引用完而失败

aa
ab
ac
ad
ae
af
ag
ah
ai
aj
ak
al
.
.
.
zz

IndexError

最佳答案

您可以使用 itertools.product() :

from itertools import product
from string import ascii_lowercase

for i in range(1, 4):
    for x in product(ascii_lowercase, repeat=i):
        print(''.join(x))

首先,您需要所有字母,然后是所有字母对,然后是所有三元组,等等。这就是为什么我们首先需要遍历您想要的所有字符串长度(for i in range(...)).

然后,我们需要与 i 字母的所有可能关联,因此我们可以使用 product(ascii_lowercase),这相当于嵌套的 for 循环重复 i 次。

这将生成所需大小为 i 的元组,最后只需 join() 它们即可获得一个字符串。

要无限制地连续生成名称,请将 for 循环替换为 while:

def generate():
    i = 0
    while True:
        i += 1
        for x in product(ascii_lowercase, repeat=i):
            yield ''.join(x)

generator = generate()
next(generator)  # 'a'
next(generator)  # 'b'
...

关于python - 创建按字母顺序升序的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53426258/

相关文章:

Python数据框: clean data of one column by comparing values from other columns

python - RLLib - Tensorflow - InvalidArgumentError : Received a label value of N which is outside the valid range of [0, N)

mysql - 改进 SQL 命令以按字母顺序显示前面和后面的值

C# 按字母顺序对字符串数组进行排序,注意将以大写字母开头的字符串放在前面。第一的

python - 函数定义如范围

python - 如何在 Django 中获取原始请求 header ?

python - 通过二维索引提取轴

c - C 中的字符串排序

javascript - 按字母顺序排列项目列表

c++ - 将两个 vector 中的元素按字母顺序排列到一个 vector 中