繁体   English   中英

是否可以遍历 python 中的运算符(大于/小于)?

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

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

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

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

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

我如何 go 关于循环关系运算符而不让 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}"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM