简体   繁体   English

For 循环 n 次迭代-Python

[英]For Loop for n iterations-Python

I have a simple For Loop in a python script:我在 python 脚本中有一个简单的 For 循环:

for filename in filenames:
    outline= getinfo(filename)
    outfile.write(outline)

This For Loop is part of a larger script that extracts data from HTML pages.这个 For 循环是从 HTML 页面提取数据的更大脚本的一部分。 I have nearly 6GB of html pages and want to do some test runs before I try it on all of them.我有将近 6GB 的 html 页面,想在对所有页面进行尝试之前进行一些测试运行。

I have searched but cant find a way to make my For Loop break after n iterations (lets say 100.)我已经搜索过,但找不到一种方法来让我的 For 循环在 n 次迭代后中断(比如 100 次)。

for filename in filenames[:100]:
    outline= getinfo(filename)
    outfile.write(outline)

The list slice filenames[:100] will truncate the list of file names to just the first 100 elements.列表 slice filenames[:100]会将文件名列表截断为前 100 个元素。

Keep a counter for your for loop.为您的 for 循环保留一个计数器。 When your counter reaches, 100, break当你的计数器达到 100 时,打破

counter = 0
for filename in filenames:
    if counter == 100:
        break
    outline= getinfo(filename)
    outfile.write(outline)
    counter += 1

I like @kqr's answer, but just another approach to consider, instead of taking the first 100, you could take a random n many instead:我喜欢@kqr 的回答,但只是另一种考虑的方法,而不是取前 100 个,您可以取一个随机的n

from random import sample
for filename in sample(filenames, 10):
    # pass

Use the built-in function enumerate() , available in both Python 2 and 3.使用内置函数enumerate() ,可在 Python 2 和 3 中使用。

for idx,filename in enumerate(filenames):
    if idx == 100:
        break
    outline= getinfo(filename)
    outfile.write(outline)

Also look at this .也看看这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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