在perl中,要获取从“a”到“azc”的所有字符串的列表,要做的只是使用范围运算符:
perl -le 'print "a".."azc"'
我想要的是一个字符串列表:
["a","b",...,"z","aa","az","ba","azc"]
我想我可以使用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']
但对我的情况来说有点复杂,在这里.
谢谢你的帮助 !
解决方法
发电机版本:
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在评论中提问:
I have no idea what I should do if I want to print from ‘b’ to ‘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