按顺序生成字母数字字符串

2024-09-28 20:56:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个循环来生成和打印字符串,如下所示:

  1. 仅限字母数字字符:
  2. 0-9在A-Z之前,也就是A-Z之前
  3. 长度可达4个字符。

所以,它会打印:

  1. 0-z中的所有字符串
  2. 然后从00 zz开始
  3. 从000 zzz开始
  4. 然后从0000 zzzz开始

然后就停了。


Tags: 字符串字母数字字符zzz个字符zzzzzz
3条回答

我不喜欢前面给出的使用product的答案,因为在python文档中查看它的实现,它似乎在开始产生结果之前将整个事情扩展到内存中的一个列表中。

这对你的案子很不利,因为正如agf自己所说,这里的排列数量巨大(远远超过一百万)。在这种情况下,创建了yield语句,这样就可以动态生成大量列表,而不是在内存中跨越(我也不喜欢在range中完全适用于xrange的浪费性range)。

我想要这样的解决方案:

def generate(chars, length, prefix = None):
    if length < 1:
        return
    if not prefix:
        prefix = ''
    for char in chars:
        permutation = prefix + char
        if length == 1:
            yield permutation
        else:
            for sub_permutation in generate(chars, length - 1, prefix = permutation):
                yield sub_permutation

这样,内存中的所有跨度都是一个递归堆栈“n”深,其中“n”是排列的长度(在本例中为4),每次只返回一个元素。

chars是一组可供选择的字符,长度为4,其用法与products非常相似,只是它在运行时不跨越内存中的整个列表。

我今天把它编码了。它完全符合您的要求。它也是可扩展的

def lastCase (lst):
    for i in range(0, len(lst)):
        if ( lst[i] != '_' ):
            return False
    return True


l = [''] * 4 #change size here if needed. I used 4
l[0] = '0'
index = 0

while ( not lastCase(l) ):

    if ( ord(l[index]) > ord('_') ):
        l[index] = '0'
        index += 1
        while( l[index] == '_' ):
            l[index] = '0'
            index += 1
        if (l[index] == ''):
            l[index] = '0'

    #print or process generated string
    print(''.join(l))

    l[index] = chr(ord(l[index]) +1)

    if ( ord(l[index]) > ord('9') and ord(l[index]) < ord('A') ):
        l[index] = 'A'
    elif ( ord(l[index]) > ord('Z') and ord(l[index]) < ord('_')  ): 
        l[index] = '_'

    index = 0

print (''.join(l))
from string import digits, ascii_uppercase, ascii_lowercase
from itertools import product

chars = digits + ascii_uppercase + ascii_lowercase

for n in range(1, 4 + 1):
    for comb in product(chars, repeat=n):
        print ''.join(comb)

这首先生成一个包含所有数字、大写字母和小写字母的字符串。

然后,对于从1到4的每个长度,它打印这些数字和字母的每个可能组合。

记住,这是很多组合——62^4+62^3+62^2+62。

相关问题 更多 >