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?
Answers:
You can take only the first count
file names with myfiles[:count]
or itertools.islice(myfiles, count)
.
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)
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])
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
.
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?
You can take only the first count
file names with myfiles[:count]
or itertools.islice(myfiles, count)
.
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)
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])
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
.