在Perl中,从"A"到"AZC"让所有的字符串列表,以使用范围运算符做唯一的事情:
perl -le 'print "a".."azc"'
Run Code Online (Sandbox Code Playgroud)
我想要的是一个字符串列表:
["a", "b", ..., "z", "aa", ..., "az" ,"ba", ..., "azc"]
Run Code Online (Sandbox Code Playgroud)
我想我可以用ord和chr,循环一遍又一遍,这是简单的获得"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']
Run Code Online (Sandbox Code Playgroud)
但对我的情况来说有点复杂,在这里.
谢谢你的帮助 !
生成器版本:
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
Run Code Online (Sandbox Code Playgroud)
编辑: @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
Run Code Online (Sandbox Code Playgroud)