Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
For循环For n迭代Python_Python_Python 2.7_For Loop - Fatal编程技术网

For循环For n迭代Python

For循环For n迭代Python,python,python-2.7,for-loop,Python,Python 2.7,For Loop,我在python脚本中有一个简单的For循环: for filename in filenames: outline= getinfo(filename) outfile.write(outline) 这个For循环是从HTML页面提取数据的较大脚本的一部分。我有将近6GB的html页面,在对所有页面进行测试之前,我想先进行一些测试 我已经搜索过了,但找不到在n次迭代(比如100次)后使For循环中断的方法。为For循环保留一个计数器。当你的计数器达到100时,停止 count

我在python脚本中有一个简单的For循环:

for filename in filenames:
    outline= getinfo(filename)
    outfile.write(outline)
这个For循环是从HTML页面提取数据的较大脚本的一部分。我有将近6GB的html页面,在对所有页面进行测试之前,我想先进行一些测试


我已经搜索过了,但找不到在n次迭代(比如100次)后使For循环中断的方法。

为For循环保留一个计数器。当你的计数器达到100时,停止

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

列表片段<代码>文件名[:100 ] < /代码>将文件名列表截断到前100个元素。

< P>我喜欢@ KQR的答案,但只是另一个考虑的方法,而不是采用前100个,你可以随机抽取<代码> N>代码>许多代替:

from random import sample
for filename in sample(filenames, 10):
    # pass
使用Python2和Python3中提供的内置函数

对于idx,枚举中的文件名(文件名):
如果idx==100:
打破
outline=getinfo(文件名)
输出文件。写入(大纲)

另请看。

如果计数器等于100,请使用计数器并中断。保留计数器的首选方法是在enumerate(文件名)中为(计数器,文件名)执行
。对于常规迭代器(不一定是列表):
对于itertools中的文件名。islice(文件名,100):
@chepner在Python 3中也有必要吗?是的;不能对任意迭代器使用切片语法。我认为这是一个更好的解决方案,只要它没有任何糟糕的性能问题。@kqr我担心的主要问题是复制能力。。。。因此,也许折衷的办法是取而代之的是n中取1,这可以通过切片很好地完成,如您的答案所示。。。而且对于测试来说还是更有用的…是的,我也这么认为,但是被放弃了,因为它可能有类似于随机抽样的性能。我没有考虑可测试性,但你确实是对的。
from random import sample
for filename in sample(filenames, 10):
    # pass