1

根据用户输入,我有不同的条件要在我的数组中检查。假设最多有 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))

上帝禁止我添加另一个条件。事情变得非常混乱。我正在寻找一种动态添加条件的方法,就好像它只是一个常规字符串或格式化程序一样。那可能吗?

4

2 回答 2

2

如果将默认值设置为 true 条件:

import numpy as np


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])


def get_id(**kwargs):
    """ a must be 1, b must be positive, c must be True """
    a = kwargs.get("a", np.ones(5))
    b = kwargs.get("b", np.ones(5))
    c = kwargs.get("c", np.ones(5) == 1)
    return np.where((a == 1) & (b > 0) & c)


print(get_id(a=a))
print(get_id(a=a, c=c))
print(get_id(a=a, b=b))
print(get_id(a=a, b=b, c=c))


(array([0, 1, 2, 4]),)
(array([0, 2, 4]),)
(array([0, 1, 4]),)
(array([0, 4]),)
于 2020-03-24T15:27:23.190 回答
1

也许以下内容可以提供帮助:

myArr = np.random.rand(5)
size = myArr.size
all_true = np.repeat(True, size)

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 if 'a' in locals() else all_true) & 
                         (b > 0 if 'b' in locals() else all_true) & 
                         (c == True if 'c' in locals() else all_true))

通过这种方式,您可以编写所有条件,并且只检查变量是否存在于局部变量中'a' in locals()。如果您在某个函数中定义a,bc在某个地方引用它们,您可以使用 . 检查它们是否在全局环境中定义'a' in globals()

于 2020-03-24T15:23:43.490 回答