避免使用多个if语句

2024-09-30 02:31:18 发布

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

我试图创建一个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值,直到每次迭代都满足上面的条件。我该怎么做?你知道吗


Tags: inforifnprangerandomabs语句
3条回答

如果我没弄错的话,这个应该可以:

df['B10'] = np.random.randint(0, df.shape[0], df.shape[0])
df['T10'] = df['B10'].apply(lambda x: np.random.randint(0, x+1))

通过生成所需的随机数来避免循环和if语句。在您的代码中,T10将是一个介于max(0,B10-30)和min(UB,B10+10)之间的随机值,包括两者。你知道吗

max_delta = 30
B10 = np.random.randint(0, UB)
T10 = np.random.randint(max(0, B10 - max_delta), min(UB, B10 + max_delta  + 1))

其中UB=精确形状[0]. 你知道吗

使用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循环。你知道吗

相关问题 更多 >

    热门问题