python 为什么我的itertools.combinations内容在我开始一个循环时就消失了?[duplicate]

dgiusagp  于 2023-01-08  发布在  Python
关注(0)|答案(1)|浏览(114)
    • 此问题在此处已有答案**:

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

我只是不明白为什么它消失了,没有什么可以循环通过。有人能好心帮助吗?非常感谢!

4xrmg8kj

4xrmg8kj1#

您可以将其设置为列表以进行持久化:

image_pairs = list(combinations(images, 2))

combinations返回生成器,而不是内存中的列表。

相关问题