0

There are several image files in a directory on which I need to iterate through, where need to access the next iteration value in the current iteration.

img_files_list = os.listdir(/path/to/directory)
new_list = []
for index, img in enumerate(img_files_list):
    if img in new_list:
        continue
    new_list.extend([img, img_files_list[index + 1], img_files_list[index + 2]])
    print(img)
    print(img_files_list[index + 1])
    print(img_files_list[index + 2])

I need to iterate over all the items of the img_files_list but when reached at the end of the loop need to properly come out of loop without index out of range exception. Anyone, please point out where do I missed the logic.

4

2 回答 2

2

看起来更像代码审查而不是堆栈溢出。

当您到达for image, img in enumerate(img_files_list)行中的最后一项时,最后一项之后没有任何项目。这就是导致IndexOutOfRangeException.

有几种方法可以解决这个问题:

  1. 正如 Sruthi V. 所写,包括一个条件:

    print(img_files_list[i])
    if i + 1 < len(img_files_list):
        print(img_files_list[i + 1])
    if i + 2 < len(img_files_list):
        print(img_files_list[i + 2])
    
  2. 包括一个try... except

    try:
        print(img_files_list[i])
        print(img_files_list[i + 1])
        print(img_files_list[i + 2])
    except IndexOutOfRangeException:
        pass
    
  3. 限制循环的范围:

    i_img = list(enumerate(['a', 'b', 'c', 'd', 'e']))
    for i, img in i_img [:len(i_img ) - 2]:
        print(img)
        print(i_img[i + 1])
        print(i_img[i + 2])
    

请注意,您没有理由使用enumerate- 您只是使用它来获取索引。你也不需要你的if img in new_list——你只是用它来跳过接下来的两个。您可以使它更优雅并使用范围解决您的问题(修改后的解决方案 3)。

imgs = os.listdir('/path/to/directory')
triplets = []
for i in range(0, len(imgs) - 2, 3):
    triplet = [imgs[i], imgs[i + 1], imgs[i + 2]]
    triplets.extend(triplet)
    print('\n'.join(triplet))

注意我不确定你甚至想做什么。甚至您if img in new_list也可能是一个错误,因为它只是跳过了最后 1-2 个最终项目。如果没有了,你要做的就是复制这个列表并打印它的内容。在这种情况下,我会建议:

imgs = os.listdir('/path/to/directory')
print('\n'.join(imgs))

但是,如果您澄清了您要执行的操作,我可以编辑此答案。

于 2018-09-16T13:15:46.363 回答
0

从我对您的问题的评论:

index + 1index + 2导致最后 2 个项目出现问题。例如,如果您的列表大小为 10,则索引将为 0,2,...,9。当索引为 8 和 9 时,您正在尝试执行 img_files_list[10]and img_files_list[11]。所以索引超出范围。

我假设您想以 3 项列表的形式访问图像,那么我建议您采用一些不同的方式。为了更好地理解,我将使用整数数组而不是图像。

img_files_list = [0,1,2,3,4,5,6,7,8,9]
new_list = []  
n = 3
for i in range(0, len(img_files_list), n): # Respectively, i is 0,3,6,9,...
    temp = img_files_list[i:i+n]
    print(temp)
    new_list.extend(temp)

输出:

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
于 2018-09-16T13:21:06.170 回答