当代码在python中运行了x次时,如何在代码中运行函数的特定部分?

2024-09-28 22:21:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有几个函数的代码,代码的迭代次数是10次

def vectfit_auto(f, s, n_poles=5, n_iter=10,loss_ratio=1e-2, rcond=-1,):

for _ in range(n_iter):
    poles, Zeros, H = vectfit_step(f, s, poles)


    poles_list.append(poles)

我想在vectfit_step(我的一个函数)中添加一些行,如下所示进行修改:

from iteration number of 5 to 10
do something

我希望代码像以前一样运行,并且我的修改只能从迭代次数5一直应用到最后。 我该怎么做? 谢谢


Tags: 函数代码inforautodefsteprange
2条回答

如前所述,可以在循环中包含if语句,并且只在主循环运行一定次数后才让它运行

for i in range(6): # 11 - 5
    if i == 5:
        for i in range(5):
            do_something()
     # main code here
#i takes values between begin and (end - 1)
for i in range(begin, end):
   do_something()

#In your case start = 5 and end = 11
for i in range(5, 10+1):
   do_something(i)

#You might use _, if you are not interested in the value of i
for _ in range(5, 11):
   do_something()

相关问题 更多 >