Skip to main content
 首页 » 编程设计

python之避免使用多个 if 语句

2025年05月04日16zhoujg

我正在尝试创建一个 if 语句来检查每次迭代的条件

          for in range(100): 
            B10 = np.random.randint(0, precip.shape[0]) 
            T10 = np.random.randint(0, precip.shape[0] ) 
 
            if np.abs(B10-T10) <=30: 
                T10 = np.random.randint(0, precip.shape[0]) 

我想创建一个 if 条件,它将获取 T10 的新值,直到每次迭代都满足上述条件。我该怎么做?

请您参考如下方法:

使用 while 循环代替 for 循环:

B10 = np.random.randint(0, precip.shape[0]) 
T10 = np.random.randint(0, precip.shape[0]) 
while np.abs(B10-T10) <= 30: 
    B10 = np.random.randint(0, precip.shape[0]) 
    T10 = np.random.randint(0, precip.shape[0]) 

或者您可以使用以下方法避免重新声明变量:

while True: 
    B10 = np.random.randint(0, precip.shape[0]) 
    T10 = np.random.randint(0, precip.shape[0]) 
    if not (np.abs(B10-T10) <=30): 
        break 

一般来说,当您知道循环的迭代次数或使用集合时,使用 for 循环是一种很好的做法。但是,当您不知道它时,即当它取决于条件时,您应该使用 while 循环。