如何有效地检查多个条件并在为true时分配不同的id?

2024-04-16 10:51:36 发布

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

我设置了一些代码,需要检查许多不同的条件,例如:

cond = np.zeros_like(matrix1)
ids = np.where(matrix1 == value1)
cond[ids] = 1
ids2 = np.where(matrix2 == value2)
cond[ids2] = 2

...

idsn = np.where(matrixn == valuen)
cond[idsn] = n

我想知道有没有更简单的方法。一般来说,这些条件彼此之间并不相关。我应该提到的是,有些矩阵可能会被重复使用(即条件5是用矩阵2检查某些东西),有些条件可能比“矩阵等于一个数”更复杂。我在寻找类似的东西:

for j, condition in enumerate(condition_list):
    ids = np.where(condition)
    cond[ids] = j

Tags: 代码idsnpzeros矩阵wherecondition条件
1条回答
网友
1楼 · 发布于 2024-04-16 10:51:36

为了保持整洁,您可以创建一个条件字典。你知道吗

def eval_equal(a, b):
    return a == b

def eval_different(a, b):
    return a != b

def eval_combination(a, b):
    eval_equal(a, b) and eval_different(a, b)

evaluator = {}
evaluator['cond1'] = eval_equal
evaluator['cond2'] = eval_different
evaluator['cond3'] = eval_combination

my_matrix = [[1, 2, 3], [1, 2, 3]]
vector = [1, 2, 3]
conds = []
for cond, eval_func in evaluator.items():
    if eval_func(my_matrix, vector):
        conds.append(cond)

print(conds)

然后,正如@pzp所说,您可以创建一个要求值的对象列表,并将它们提供给字典,字典将遍历所有条件。此外,它还允许您组合简单条件(或更复杂的条件,如a>;10+b),因为它们都是函数。你知道吗

相关问题 更多 >