简体   繁体   English

永久更改 python 中 for 循环内的参数公式

[英]Permanently change of the formula of a parameter inside a for loop in python

I want to run a nested for loop in python, where it should run until a specific threshold of a variable, defined in the loop.我想在 python 中运行一个嵌套的 for 循环,它应该运行到循环中定义的变量的特定阈值。 After the threshold, I would like to continue the loop and change the formula of the parameter permanently.在阈值之后,我想继续循环并永久更改参数的公式。 I hope with the following example, that I will be able to show you what I want to do.我希望通过以下示例,我将能够向您展示我想要做什么。

import numpy as np
a=np.linspace(1,10,10)
b=np.linspace(0,20,10)

t=np.zeros([len(a),len(b)])

for i in range(0,len(a)):
    for j in range(0,len(b)):
        t[i,j]=a[i]+3*b[j]
        if t[i,j]>30:
           t[i,j]=a[i]+b[j]
        else:
           continue      

In the specific loop the equation of t changes when the threshold value is reached and afterwards it goes back to the initial and continues in the loop.在特定循环中,当达到阈值时,t 的方程会发生变化,然后它会回到初始值并继续循环。 My aim is after the threshold value, to change permanently the equation of t and continue with that for the rest of the loop.我的目标是在阈值之后,永久改变 t 的方程并继续循环的 rest 的方程。

You might like to use an additional variable to indicate if you have reached your desired criterion to switch to a different function:您可能想使用一个附加变量来指示您是否已达到所需的标准以切换到不同的 function:

Example:例子:

import numpy as np
a=np.linspace(1,10,10)
b=np.linspace(0,20,10)

t=np.zeros([len(a),len(b)])

threshold_flag = False
for i in range(0,len(a)):
    for j in range(0,len(b)):
        if threshold_flag:
            t[i,j] = a[i] + b[j]
        else:
            t[i,j]=a[i]+3*b[j]
            if t[i,j]>30:
               t[i,j] = a[i] + b[j]
               threshold_flag = True
            else:
               continue

Do you mean something like this?你的意思是这样的吗?

import numpy as np
a=np.linspace(1,10,10)
b=np.linspace(0,20,10)

t=np.zeros([len(a),len(b)])

THRESHOLD = 30
reached_threshold = False

for i in range(0,len(a)):
    for j in range(0,len(b)):
        if not reached_threshold:
            t[i,j]=a[i]+3*b[j]
            if t[i,j] > THRESHOLD:
                reached_threshold = True
                t[i,j]=a[i]+b[j] 
        else:
            t[i,j]=a[i]+b[j]   

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

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