首页 > 解决方案 > 避免使用多个 if 语句

问题描述

我正在尝试创建一个 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 的新值,直到每次迭代都满足上述条件。我怎样才能做到这一点?

标签: pythonpandasnumpy

解决方案


使用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循环。


推荐阅读