是否可以在 python 中循环运算符(大于 than/less)?

Is it possible to loop through operators (greater than/less than) in python?

我希望能够遍历关系运算符。我有以下代码工作:

TP = df[(df.Truth == 1) & eval(df.age >= cutoff)]

我还有几行,其中真值和关系运算符不同,但其他一切都相同。 我尝试创建一个列表并使用 eval 函数,但我知道这是错误的,因为我什至无法克服语法错误。

truths = [[1,'>='],[0,'>='],[1,'<'],[0,'<']]
for truth in truths:
     truth_val = truth[0]
     operator = truth[1]
     TP = df[(df.Truth == truth) & eval(df.age operator cutoff)]

如何循环关系运算符而不是 python 将其作为字符串而是作为实际运算符? 提前致谢!!!

如果你想要实际的运算符,那么你应该使用 operator 库:

import operator as op

那么您的代码应该如下所示:

truths = [[1, op.ge], [0, op.ge], [1, op.lt], [0, op.lt]]
for truth in truths:
  truth_val = truth[0]
  operator = truth[1]
  TP = df[(df.Truth == truth) & operator(df.age, cutoff)]

这是最安全的解决方案,强烈反对所有基于 eval 的解决方案,在运行时评估字符串是一个潜在的安全问题。

你能试试吗

truths = [[1,'>='],[0,'>='],[1,'<'],[0,'<']]
for truth in truths:
     truth_val = truth[0]
     operator = truth[1]
     TP = df[(df.Truth == truth) & eval("df.age"+ operator + cutoff)] # notice cutoff here should be string

您需要 eval() 提供一个字符串:

truths = [[1,'>='],[0,'>='],[1,'<'],[0,'<']]
for truth in truths:
     truth_val = truth[0]
     operator = truth[1]
     print(eval(f"{df.age}{operator}{cutoff}"))