简体   繁体   中英

python for in looping n times

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?

您只能使用myfiles[:count]itertools.islice(myfiles, count)获取第一个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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM