Python 中如何表示 perl 的 "a".."azc"?

7 投票
6 回答
1823 浏览
提问于 2025-04-16 01:23

在perl中,如果你想要获取从"a"到"azc"的所有字符串,最简单的方法就是使用范围操作符:

perl -le 'print "a".."azc"'

我想要的是一个字符串列表:

["a", "b", ..., "z", "aa", ..., "az" ,"ba", ..., "azc"]

我想我可以使用ordchr这两个函数,反复循环,这样可以很简单地得到从"a"到"z"的字符串,比如:

>>> [chr(c) for c in range(ord("a"), ord("z") + 1)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

不过对于我的情况来说,这就有点复杂了。

谢谢大家的帮助!

6 个回答

2

在这个例子中,我们可以使用itertools库里的product函数,还有string库里的ascii_letters。这样可以帮助我们生成一些组合或者排列。

from string import ascii_letters
from itertools import product

if __name__ == '__main__':
    values = []
    for i in xrange(1, 4):
        values += [''.join(x) for x in product(ascii_letters[:26], repeat=i)]

    print values
4

这是一个纯粹基于迭代器的建议:

import string
import itertools

def string_range(letters=string.ascii_lowercase, start="a", end="z"):
    return itertools.takewhile(end.__ne__, itertools.dropwhile(start.__ne__, (x for i in itertools.count(1) for x in itertools.imap("".join, itertools.product(letters, repeat=i)))))

print list(string_range(end="azc"))
5

生成器版本:

from string import ascii_lowercase
from itertools import product

def letterrange(last):
    for k in range(len(last)):
        for x in product(ascii_lowercase, repeat=k+1):
            result = ''.join(x)
            yield result
            if result == last:
                return

编辑: @ihightower 在评论中问:

如果我想从 'b' 打印到 'azc',我该怎么做?我完全不知道。

所以你想从 'a' 以外的地方开始。只需要忽略开始值之前的任何东西:

def letterrange(first, last):
    for k in range(len(last)):
        for x in product(ascii_lowercase, repeat=k+1):
            result = ''.join(x)
            if first:
                if first != result:
                    continue
                else:
                    first = None
            yield result
            if result == last:
                return

撰写回答