用于评估字符串表达式的eval()的替代方法

时间:2017-07-17 19:04:20

标签: python eval

我想知道是否有一种简单的方法可以避免在以下代码中使用eval:

eval('6001 >= 6005')

我一直在寻找几个小时试图找到一个简单的替代品,因为学习eval并不是一个好习惯,特别是当你不知道谁将会使用该程序时。

我使用它的背景是这样的:

两个比较变量中的每一个都是pandas dataframe列中的值,因此它也可能如下所示:

eval('"my_city_name" == "your_city_name"')

非常感谢任何帮助!感谢

2 个答案:

答案 0 :(得分:1)

您可以通过实施您想要允许的比较来避免eval()

STRINGS = ['6001 >= 6005', '"my_city_name" == "your_city_name"', '13 != 14', '1 < 4']

COMPARISONS = {
    '==': lambda a, b: a == b,
    '!=': lambda a, b: a != b,
    '>=': lambda a, b: a >= b,
}

for string in STRINGS:
    operand1, comparison, operand2 = string.split()

    if comparison in COMPARISONS:
        print(string, (COMPARISONS[comparison])(operand1, operand2))
    else:
        print(string, "Unknown comparison")

这只是一个例子,实际上你需要做一些类型检查,数字转换等等,但关键是要确定哪些比较对你很重要。

答案 1 :(得分:0)

以下是我最终的结果:

def transform(self, attribute):

    try:
        attribute = float(attribute)
        if math.isnan(attribute):
            attribute = "NULL"
            print type(attribute)
            return attribute
    except ValueError:
        attribute = str(attribute)

    print type(attribute)
    return attribute

def equals(self, attribute, value):
    return self.transform(attribute) == self.transform(value)

def not_equals(self, attribute, value):
    return self.transform(attribute) != self.transform(value)

def greater_than(self, attribute, value):
    return self.transform(attribute) > self.transform(value)

def greater_than_equal(self, attribute, value):
    return self.transform(attribute) >= self.transform(value)

def less_than(self, attribute, value):
    return self.transform(attribute) < self.transform(value)

def less_than_equal(self, attribute, value):
    return self.transform(attribute) <= self.transform(value)

由于我只需要少数几个操作员,这是我能想到的最好的解决方案。 transform()只是为了处理我在特定数据集中遇到的一些比较问题。希望这可以帮助将来的某个人!如果有人有任何意见或建议,请告诉我。

相关问题