Python - how to for loop an array from not 0th but xth element?

Viewed 58

I have a for loop like this

ImgPaths = make_dataset(TestImgPath)
    for i, ImgPath in enumerate(ImgPaths):

In which:

  • TestImgPath is the path to input images. Type string. In my case TestImgPath = './TestData/TestWhole'. TestData and TestWhole are folders.
  • ImgPath is the path to image. For example ImgPath = ./TestData/TestWhole\XXXXX.jpg when I print. XXXXX is 00000 to 82700 in my case
  • ImgPath is the path to images at once. For example ImgPaths = ./TestData/TestWhole\\XXXXX.jpg when I print. But I think it is the entire 00000-XXXXX in one, since ImgPaths is assigned like above.

So, there are 82700 files to handle, and it takes 24 seconds for one file. Wait for it to be done entirely at once is too long. The parent folder is large so I cannot duplicate the parent folder into 10 copies and execute every single copy. So dividing that for loop may be the way to go. Seems like it is not a normal for loop but an array for loop.

So, how to make an array for loop start and stop at a certain element? If I want to start from 11111.jpg and stop at 22222.jpg, how to do it?

This is the source code https://drive.google.com/file/d/1jnE7kSK2eyXEAsTXb_4IctUEbBkZSWJa/view?usp=sharing

Thank you.

1 Answers

You can use a conditional statement to skip processing until i reaches the desired starting number, and then break the loop when i exceeds the ending number:

for i, ImgPath in enumerate(ImgPaths):
    if i > 22222:
        break
    elif i >= 11111:
        # process ImgPath

or use itertools.islice to limit the iterations to the specified range:

import itertools
for ImgPath in itertools.islice(ImgPaths, 11111, 22222 + 1):
    # process ImgPath
Related