How can I process at most a certain number of elements from a list?

Question:

Using looping as follows to list n files from a directory:

myfiles = glob.glob("*.xml")
files = len(myfiles)

count = 0
myfiles.sort()
files_to_process = 3
for filename in myfiles:
   count += 1
   print (time.strftime("%I:%M:%S"), count ,'of', files, '|', filename)
   if count == files_to_process:
      break

is there an alternative way to iterate only through n times other than using break?

Asked By: haz

||

Answers:

You can take only the first count file names with myfiles[:count] or itertools.islice(myfiles, count).

Answered By: satoru

Try this:

myfiles = glob.glob("*.xml")
files = len(myfiles)

count = 0
myfiles.sort()
files_to_process = 3
for filename in myfiles[:files_to_process]:
   count += 1
   print (time.strftime("%I:%M:%S"), count ,'of', files, '|', filename)
Answered By: Paul Whipp
myfiles = glob.glob("*.xml")
files = len(myfiles)

myfiles.sort()
files_to_process = 3

for i in range(min(files_to_process, files)):
  print (time.strftime("%I:%M:%S"), i+1 ,'of', files, '|', myfiles[i])
Answered By: kg1313

Here’s a way using zip: the behaviour is to stop after exhausting whichever sequence is shorter. Zipping with a range also saves you having to manually update a counter.

myfiles = glob.glob("*.xml")
files = len(myfiles)

myfiles.sort()
files_to_process = 3

for filename, count in zip(myfiles, range(1, files_to_process+1)):
    print(time.strftime("%I:%M:%S"), count, 'of', files, '|', filename)

That said, this solution is not idiomatic, and I don’t think the code is better than the version using break.

Answered By: kaya3
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.