2 回答

TA貢獻1820條經驗 獲得超10個贊
你知道你的名單會有多長嗎?它是 36**6 = 2176782336 項。有點太多記不住了。您應該使用生成器:
dictionary = 'abcdefghijklmnopqrstuvwxyz0123456789'
for x in itertools.product(dictionary, repeat=6):
print(''.join(x))

TA貢獻1946條經驗 獲得超4個贊
排列的大小是巨大的:36^6!那是 2176782336 個字符串。由于 python 存儲單獨對象的方式,python 中的 6 字符字符串已經相對較大。
from sys import getsizeof
getsizeof('aaaaaa') # 55
每個字符串 55 個字節,整個列表幾乎是 120 GB。您的機器上可能沒有太多內存。
如果您嘗試將此迭代器轉換為列表,它將立即生成所有排列。您可以做的是使用返回的迭代器itertools.product(dictionary, repeat=6)而不將其轉換為列表。
for s in itertools.product(dictionary, repeat=6):
# Do something with the string, such as writing it to a file.
在不知道您要對產品做什么的情況下,我無法具體告訴您如何優化它。但我仍然可以說嘗試將此迭代器轉換為 alist是一個壞主意。
添加回答
舉報