简体   繁体   English

Python:循环浏览字母

[英]Python: Cycle Through the Alphabet

I'm creating a script that cycles through the alphabet, after that a new letter is added that cycles through again. 我正在创建一个脚本,该脚本可以循环浏览字母,然后添加一个新字母,可以再次循环浏览。 Here's my code so far: 到目前为止,这是我的代码:

import string
for a in (string.ascii_letters + string.digits):
    print (a)
for a in (string.ascii_letters + string.digits):
    for b in (string.ascii_letters + string.digits):
        print(a + b)
for a in (string.ascii_letters + string.digits):
    for b in (string.ascii_letters + string.digits):
        print(a + b)
        for c in (string.ascii_letters + string.digits):
            print(a + b + c)

What is a more efficient way of doing this? 什么是更有效的方法?

The itertools module will let you define an infinite stream of such strings. itertools模块将允许您定义此类字符串的无限流。

import string
import itertools

def alphanumeric_strings():
    for n in itertools.count():
        for t in itertools.product(string.ascii_letters + string.digits, repeat=n):
            yield ''.join(t)

for x in alphanumeric_strings():
    print x

count simply produces an infinite stream of integers counting up from 1, so that each time you call product , you get a stream of tuples with one more digit than the last. count简单地产生一个无限的整数流,从1开始向上计数,因此每次调用product ,您将得到一个元组流,其中元组的位数比最后一位多。 The call to join converts a tuple like ('a', 'B', '1') to the string aB1 . join调用将类似('a', 'B', '1')的元组转换为字符串aB1

You can use itertools.product , which is "equivalent to nested for-loops in a generator expression": 您可以使用itertools.product ,它“等效于生成器表达式中的嵌套for循环”:

import itertools
import string
ALPHABET = string.ascii_letters + string.digits
for a in itertools.product(ALPHABET, repeat=1):
    print(a)
for a,b in itertools.product(ALPHABET, repeat=2):
    print(a + b)
# etc.

Using itertools: 使用itertools:

import string
from itertools import count, product

def words(chars=string.ascii_letters + string.digits):
    for n in count(1):
        yield from map(''.join, product(chars, repeat=n))

Not using itertools: 不使用itertools:

import string

def words(chars=string.ascii_letters + string.digits):
    yield from chars
    for word in words(chars):
        for char in chars:
            yield word + char

Both produce all words made from the given characters: 两者都产生由给定字符组成的所有单词:

for word in words('aB3'):
    print(word)

Prints: 印刷品:

a
B
3
aa
aB
a3
Ba
BB
B3
3a
3B
33
aaa
aaB
...

Another way: 其他方式:

abc = {0:"", 1:"", 2:""}

end = ""

for i in range(len(abc)):

    for letter in …:

        abc[i] = letter

        end = abc[0] + abc[1] + abc[2]

        print(end)

A simple way without itertools and variable amount of letters. 没有itertools和数量可变的字母的简单方法。 Just add to the abc dictionary. 只需添加到abc字典。

The following works in Python 2 and 3. 以下内容适用于Python 2和3。

# For Python 2/3 compatibility
from __future__ import print_function

import itertools
import string


def all_words(alphabet, max_length=None):
    if max_length:
        count_range = range(1, max_length+1)
    else:
        count_range = itertools.count(1)

    for length in count_range:
        for chars in itertools.product(alphabet, repeat=length):
            yield ''.join(chars)

# Demonstration

def main():
    demo_alphabet = 'abc'
    print(list(all_words(demo_alphabet, 3)))

    print()

    alphabet = string.ascii_letters + string.digits
    print(list(itertools.islice(all_words(alphabet, 2), 124)))


if __name__ == '__main__':
    main()

The output is: 输出为:

['a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc',
 'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa',
 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab',
 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']

['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', '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', '0', '1', '2', '3',
 '4', '5', '6', '7', '8', '9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag',
 'ah', 'ai', 'aj', 'ak', 'al', 'am', 'an', 'ao', 'ap', 'aq', 'ar', 'as',
 'at', 'au', 'av', 'aw', 'ax', 'ay', 'az', 'aA', 'aB', 'aC', 'aD', 'aE',
 'aF', 'aG', 'aH', 'aI', 'aJ', 'aK', 'aL', 'aM', 'aN', 'aO', 'aP', 'aQ',
 'aR', 'aS', 'aT', 'aU', 'aV', 'aW', 'aX', 'aY', 'aZ', 'a0', 'a1', 'a2',
 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9']

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

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