如何在Python中完全循环N次?

yeg*_*gle 4 python loops

例如,我需要通过调用readline10次来读取文件.

with open("input") as input_file:
    for i in range(10):
        line = input_file.readline()
        # Process the line here
Run Code Online (Sandbox Code Playgroud)

这是一种非常常用的技术,用于range控制循环次数.唯一的缺点是:有一个未使用的i变量.

这是我从Python中获得的最好的吗?有更好的想法吗?

PS在Ruby中我们可以做到:

3.times do
  puts "This will be printed 3 times"
end
Run Code Online (Sandbox Code Playgroud)

这是优雅和非常清楚地表达意图.

Ter*_*ryA 10

这几乎是循环特定次数的最佳选择.

一个常见的习语是for _ in ...代替,代表_一种占位符.


Jam*_*ore 5

使用isliceitertools

from itertools import islice
with open("input", 'r') as input_file:
    for line in islice(input_file, 10):
        #process line
Run Code Online (Sandbox Code Playgroud)

由于您可以直接遍历文件行,因此无需调用input_file.readline() 查看itertools.islice的文档