我有一些很大的文件,我正试图用这些代码获得所有的组合
for text1, text2 in itertools.product(open('text1.txt'), open('text2.txt')):
t3 = (text1.strip() + text2.strip())
time.sleep(1)
print(t3)
使用小文件进行测试,效果很好,但当使用大文件时,什么都没有发生,我猜它会将文件加载到内存中,所以不会将整个文件加载到内存中
我有一些很大的文件,我正试图用这些代码获得所有的组合
for text1, text2 in itertools.product(open('text1.txt'), open('text2.txt')):
t3 = (text1.strip() + text2.strip())
time.sleep(1)
print(t3)
使用小文件进行测试,效果很好,但当使用大文件时,什么都没有发生,我猜它会将文件加载到内存中,所以不会将整个文件加载到内存中
这是documented:
在
product()
次运行之前,它完全消耗了输入的可重用项,
注意,在这种特殊情况下,您可以执行以下操作:
with open("text1.txt") as f1, open("text2.txt") as f2:
for text1 in f1:
for text2 in f2:
# do some stuff
t3 = (text1.strip() + text2.strip())
f2.seek(0) # reset inner file cursor
这是可能的,因为文件迭代器的性质-您可以从头开始搜索,迭代器会被有效重置(这也很好,也很有效!).但这通常不适用于iterables或迭代器,因此itertools.product
只需将迭代器的两个列表具体化即可处理一般情况