【发布时间】:2020-10-17 19:39:21
【问题描述】:
我正在尝试编写一个脚本来模拟一段时间内的化学反应系统。该函数的输入之一是以下数组:
popul_num = np.array([200, 100, 0, 0])
其中包含系统中每个物种的离散分子的数量。主要函数的一部分有一个if 语句,用于检查分子数量是否为正。 if 处理到下一次迭代,else 跳出整个模拟
if popul_num.any() < 0: # Any method isn't working! --> Does .any() work on arrays or just lists?
print("Break out of loop negative molecule numbers")
tao_all = tao_all[0:-1]
popul_num_all = popul_num_all[0:-1]
else:
break
我使用.any() 来尝试查找popul_num 数组的任何元素是否为负数。但它不起作用,它没有抛出错误,系统只是从不进入 if 语句,我不知道为什么?
我刚刚运行了这个程序,系统返回的最终分子数是:[135 -19 65 54] 程序应该在第二个元素达到 -19 之前就爆发了。
有什么建议吗?
干杯
【问题讨论】:
-
any 将在至少有一个元素为 True 时返回 True;
any(iterable) -
只需执行
if np.any(popul_num < 0): # do_stuff或if (popul_num < 0).any(): #do_stuff。您首先在应用any之前构造一个布尔数组之前。
标签: python arrays numpy if-statement any