根据用户输入,我有不同的条件要在我的数组中检查。假设最多有 3 个条件:
a 必须是 1
b 必须为正
c 必须为真
只有当这三个条件评估为 True 时,才应处理数组:
myArr = np.random.rand(5)
a = np.array([1, 1, 1, 0, 1])
b = np.array([4, 3, -8, 7, 6])
c = np.array([True, False, True, True, True])
valid_indices = np.where((a == 1) & (b > 0) & (c == True))
>> valid_indices
>> Out: (array([0, 4], dtype=int64),)
事先不知道将提供哪些条件,我将不得不像这样检查:
if a and not b and not c:
valid_indices = np.where(a == 1)
elif a and not b and c:
valid_indices = np.where((a == 1) & (c == True))
elif a and b and not c:
valid_indices = np.where((a == 1) & (b > 0))
elif not a and b and c:
valid_indices = np.where((b > 0) & (c == True))
elif not a and not b and c:
valid_indices = np.where(c == True)
elif not a and b and not c:
valid_indices = np.where((b > 0))
上帝禁止我添加另一个条件。事情变得非常混乱。我正在寻找一种动态添加条件的方法,就好像它只是一个常规字符串或格式化程序一样。那可能吗?