python - 如何最多处理列表中一定数量的元素?

标签 python loops

<分区>

使用如下循环列出目录中的 n 个文件:

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

除了使用 break 之外,还有其他方法可以只迭代 n 次吗?

最佳答案

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])

关于python - 如何最多处理列表中一定数量的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278306/

相关文章:

python - 正则表达式包括标志 ignorecase 和点匹配所有

python - 如何使用 python-vlc 从 RSTP 链接获取快照

jquery - 循环提交表单

c++ - 使用 for 循环的无符号 int 反向迭代

Java:如果使用 for-each 循环遍历集合,则可以替代 iterator.hasNext()

python - 有条件填充数据框 pandas

python - 在Spark Cluster模式下使用 Pandas 读取数据时出现异常行为

python - 使用 Google Wave 机器人做简单的事情

c++ - 使用std::list c++在不使用直接循环的情况下将文本文件读入列表

javascript - JSON数组迭代: How to apply a function on each element of a json array in javascript?