简体   繁体   English

生成范围内的连续字符串

[英]Generate continuous character strings in a range

I want to generate all strings from "aaa" down to "zzz" . 我想生成从"aaa""zzz"所有字符串。 Currently, I'm doing this using 3 for loops, is there a more pythonic way of doing this? 目前,我正在使用3 for循环来执行此操作,是否有更Python化的方式来执行此操作?

key_options = []
for n1 in range(ord('a'), ord('z')+1):
    for n2 in range(ord('a'), ord('z')+1):
        for n3 in range(ord('a'), ord('z')+1):
             key_options.append(chr(n1) + chr(n2) + chr(n3))

Use itertools.product and a list comprehension: 使用itertools.product和列表理解:

>>> from itertools import product
>>> from string import ascii_lowercase
>>> [''.join(p) for p in product(ascii_lowercase, repeat=3)]
['aaa', 'aab', 'aac', 'aad', 'aae', ..., 'zzv', 'zzw', 'zzx', 'zzy', 'zzz']

The itertools module is a much better way to do this sort of loop. itertools模块是执行此类循环的一种更好的方法。 The product function is what you'd use: 您使用的product功能如下:

itertools.product(*iterables[, repeat])

Cartesian product of input iterables. 输入迭代的笛卡儿乘积。

Equivalent to nested for-loops in a generator expression. 等效于生成器表达式中的嵌套for循环。 For example, product(A, B) returns the same as ((x,y) for x in A for y in B) . 例如, product(A, B)product(A, B) ((x,y) for x in A for y in B)相同((x,y) for x in A for y in B)返回相同的值((x,y) for x in A for y in B)

The string can provide the ASCII lowercase letters without using a range : string可以提供ASCII小写字母,而无需使用range

string.ascii_lowercase

The lowercase letters 'abcdefghijklmnopqrstuvwxyz' . 小写字母'abcdefghijklmnopqrstuvwxyz' This value is not locale-dependent and will not change. 此值不依赖于语言环境,不会更改。

Thus, you have 因此,你有

from itertools import product
from string import string

key_options = [''.join(n) for n in product(ascii_lowercase, repeat=3)]
>>> letters = [chr(i) for i in range(ord('a'), ord('z')+1)]
>>> letters
['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']

import itertools
["".join(i) for i in itertools.product(letters,letters,letters)]

Output 产量

['aaa', 'aab', 'aac', ... 'zzy', 'zzz']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM