在python中改进这个非常简单的字典生成器

时间:2011-07-26 22:06:25

标签: python

我正在尝试制作一个简单的dict生成器。它有效,但它还不是很实用。

我希望能够在不触及代码的情况下更改输出的最大大小来改进它。

letr='abcdefghijklmnopqrstuvwxyz'
for i in range(len(letr)):
    t=letr[i]
    print t
    for t2 in letr:
        print t+t2
        for t3 in letr:
            print t+t2+t3
            for t4 in letr:
                print t+t2+t3+t4
                for t5 in letr:
                    print t+t2+t3+t4+t5

3 个答案:

答案 0 :(得分:4)

import itertools

def dict_gen(n):
    letr = 'abcdefghijklmnopqrstuvwxyz'
    return itertools.chain(''.join(j) for i in range(n) 
                           for j in itertools.product(letr, repeat=i+1))

用法:

for word in dict_gen(n):  # replace n with the max word length you want
    print word

与其他一些答案不同,这将包括像你的例子('aa','bb'等)的重复。

dict_gen()将返回一个生成器,但如果您需要按索引访问元素,则可以随时将其传递给list()

>>> words = list(dict_gen(5))
>>> len(words) == 26 + 26**2 + 26**3 + 26**4 + 26**5  # verify correct length
True
>>> words[20:30]  # transition from one letter to two letters
['u', 'v', 'w', 'x', 'y', 'z', 'aa', 'ab', 'ac', 'ad']
>>> words[-10:]   # last 10 elements
['zzzzq', 'zzzzr', 'zzzzs', 'zzzzt', 'zzzzu', 'zzzzv', 'zzzzw', 'zzzzx', 'zzzzy', 'zzzzz']

答案 1 :(得分:1)

letr = ''.join(chr(o) for o in range(ord('a'), ord('z') + 1))
import itertools
print [''.join(word) for word in itertools.permutations(letr, 5)]

答案 2 :(得分:1)

Itertools是你最好的朋友。

>>> import itertools
>>> gen = ("".join(i) for i in itertools.permutations(letr, 5))
>>> list(gen)[-10:]
['zyxwm', 'zyxwn', 'zyxwo', 'zyxwp', 'zyxwq', 'zyxwr', 'zyxws', 'zyxwt', 'zyxwu', 'zyxwv']

如果你想获得所有的费用,你可以自己写一个发电机:

import itertools

def perms(seq):
     for n in range(len(seq)+1):
         for i in itertools.permutations(seq, n):
             yield i

查看itertools和generator的Python文档以获取更多信息。