Skip to main content
 首页 » 编程设计

python之我如何有效地检查许多条件并在 true 的情况下分配不同的 id

2024年10月25日1352php

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

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 

请您参考如下方法:

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

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),因为它们都是函数。