- 此问题在此处已有答案**:
Why can't I iterate twice over the same iterator? How can I "reset" the iterator or reuse the data?(5个答案)
6个月前关闭。
下面是我的python代码,用于从一系列图像中构造图像对,然后循环遍历它们:
from itertools import combinations
import os
root = "/root/code/set1/"
folders = "images"
os.chdir(root+folders)
with open(os.path.join(root, root.split("/")[-1]+"_results.txt"), 'w') as f:
metrics = ["cosine", "euclidean"]
print("starting the looop")
jresults = {}
images = os.listdir(os.path.join(root, folders))
images = [image for image in images if image.endswith(".jpg")]
image_pairs = combinations(images, 2)
print("number of pairs: {}".format(len(list(image_pairs)))) ## here it prints out correct numbers like 21325546
for metric in metrics:
print("metric: {}".format(metric))
print("number of pairs: {}".format(len(list(image_pairs)))) ## HERE IT PRINTS 0 AND I COULDN'T FIGURE OUT WHY
for img1, img2 in image_pairs:
print("img1: {}, img2: {}".format(img1, img2)) ## HERE PRINTS NOTHING
我只是不明白为什么它消失了,没有什么可以循环通过。有人能好心帮助吗?非常感谢!
1条答案
按热度按时间4xrmg8kj1#
您可以将其设置为列表以进行持久化:
combinations
返回生成器,而不是内存中的列表。