2013-01-02 60 views
1

我有一個小腳本,從python中給定的字符生成一個單詞列表。但執行後總會得到一個MemoryError。它爲什麼存儲在內存中?有沒有更好的代碼不使用內存的方式,但提供了一個工作輸出?Python MemoryError

from itertools import product 
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 
     'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 
     'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 
     'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 
     'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', 
     '4', '5', '6', '7', '8', '9'] 
length = 8 
result = ["".join(item) for item in product(*[chars]*length)] 
for item in result: 
    print(item) 
+1

順便說一句,你可以使用一個字符串:'chars = string.ascii_letters + string.digits'。 –

回答

10

通過在您的生成器中放置方括號,您可以告訴Python將它轉換爲實際的內存列表。你不一定真的需要所有的元素,是嗎?

相反,把你的方括號到括號和Python將保持發電機,要求時纔會產生項目:

>>> ("".join(item) for item in product(*[chars]*length)) 
    <generator object <genexpr> at 0x2d9cb40> 
>>> ["".join(item) for item in product(*[chars]*length)] 
[1] 3245 killed  ipython2 

看看在string模塊。它有一堆有用的常量:

import string 
from itertools import product 

chars = string.letters + string.digits 
length = 8 

result = (''.join(item) for item in product(*[chars], repeat=length)) 

for item in result: 
    print(item) 
+0

您可以*使用'repeat'關鍵詞來搜索'product':'product(* [chars],repeat = length)'。 –