python - 避免使用多个 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 的新值,直到每次迭代都满足上述条件。我怎样才能做到这一点?
解决方案
使用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
循环。
推荐阅读
- spring - OneToMany Jpa 在更新父表时不断在子表中插入重复项
- r - 在 R Shiny 中,可以在条件面板中使用多个条件吗?
- python - 如何使用 pandas 将列中的匹配值转换为字典
- vertex-shader - OpenGL es:在顶点着色器中“剔除”的最佳方式
- python - 网格中的图形深度优先搜索 (DFS)
- python - 使用skimage时如何选择正确的椭圆
- javascript - 服务器发送数据不正确
- python - 迭代lxml web元素
- python-3.x - 使用 super 与内置类型的继承 - 与列表不同的结果
- reactjs - Antd Select 搜索后显示“无数据”,即使您填充了选项