【问题标题】:How to run specific part of a function in a code when code has been run for x times in python?当代码在python中运行x次时,如何在代码中运行函数的特定部分?
【发布时间】:2019-02-22 19:51:35
【问题描述】:

我的代码有几个函数,代码的迭代次数是 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 的迭代次数到结束。 我怎样才能做到这一点? 谢谢

【问题讨论】:

  • for i in range(10): if i > 5: do something?

标签: python iterator iteration


【解决方案1】:
#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()

【讨论】:

  • 因为我们不会在任何事情上使用i,所以我建议使用_
【解决方案2】:

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

for i in range(6): # 11 - 5
    if i == 5:
        for i in range(5):
            do_something()
     # main code here

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    相关资源
    最近更新 更多