我正在尝试输出一个包含字母和数字的每个可能的6长度组合的列表。
我已经尝试了很多不同类型的代码,而且这个代码似乎是最好的,但是我使用它的长度并不长。
import itertools
import pprint
letters = ["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"]
pprint.pprint(list(itertools.product(letters, repeat=6)))
当我运行时,我收到此错误:
MemoryError
它可以重复设置为小于5的任何值。
我该如何解决这个问题?是否有更简单或更好的方法来获得相同的结果?是否可以将其输出到文本文件而不必打印它?我不在乎是否有重复,但如果没有重复,我会优先考虑。
这个网站:textmechanic.com/Combination-Generator.html也做了我想做的事情,但它不能处理我正在使用的大量对象和组合的长度。如果已经存在这样的列表,那就可以了。
或者只是不可能完成这项工作?
答案 0 :(得分:4)
您正在尝试创建一个包含36个** 6 = 2176782336元组的6个1个字符字符串的列表。那超过20亿(二十亿)。这需要至少210 GB的内存,只来保存元组对象(我的Mac上每个104字节都很小)。
不要试图制作一份清单;在生成值时打印它们然后再次丢弃它们:
for combo in itertools.product(letters, repeat=6))):
print ''.join(combo)
要将此内容写入文件,请写下str.join()
结果和换行符:
with open('outputfile.txt', 'w') as outfile:
for combo in itertools.product(letters, repeat=6))):
outfile.write(''.join(combo) + '\n')
这需要很少的内存,但你需要14GB的磁盘空间来存储20亿个7个字符(包括换行符)。
答案 1 :(得分:1)
你基本上要求在一个列表中预先生成所有这些组合,然后一次打印。
你可以做的是通过不调用list(...)
来避免这种情况,而是在迭代器生成它们时动态打印它们。
这是一个例子。它不是原始格式,但可以完成工作。
import itertools
import pprint
letters = ["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"]
for item in itertools.product(letters, repeat=6):
pprint.pprint(item)