如何迭代字母表?

时间:2017-05-11 14:32:55

标签: python python-2.7 python-3.x

如何迭代字母表并让它继续超过字母Z?例如 - a,b,c ... y,x,aa,ab,ac,ad

在momenent这是我的数组

letters = [
           "a","b","c","d","e","f","g","h","i","k",
           "l","m","n","o","p","q","r","s","t","u",
           "v","w","x","y","z", "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", "ba", "bb", "bc", "bd", "be", "bf", "bg", "bh", "bi",
           "bj", "bk", "bl", "bm", "bn", "bo", "bp", "bq", "br", "bs", "bt",
           "bu", "bv","bw", "bx", "by", "bz","ca","cb","cc","cd","ce",
           "cf","cg","ch","ci","cj","ck","cl","cm","cn","co","cp",
           "cq","cr","cs","ct","cu","cv","cw"]

但我想让它在循环中创建。

2 个答案:

答案 0 :(得分:3)

你可以试试这个:

import string

letters = list(string.ascii_lowercase)

letters.extend([i+b for i in letters for b in letters])

print letters

通过使用双循环,我们像往常一样迭代字母表,除了我们可以将迭代放在列表理解中,以节省空间并且更加pythonic。

答案 1 :(得分:1)

由于string.ascii_lowercase包含所有小写字母,您可以在一个循环(对于1个字母的字符串)或两个(对于2个字母的字符串)中迭代它们,然后将它们添加到列表,像这样:

import string
list = []
for c in string.ascii_lowercase: 
    list.append(c)

for c1 in string.ascii_lowercase:
    for c2 in string.ascii_lowercase:
        list.append(c1+c2)

print(list)