0

我是 python 新手,我需要简化这个检查器。我该如何改变:

...
if c == '>' and ( prevTime > currentTime ):
    c2 = True
elif c == '>=' and ( prevTime >= currentTime ):
    c2 = True
...

类似于:

 if  prevTime | condition |  currentTime:
    doSomething()

我尝试使用evaluatecompile,但在创建字符串期间,日期时间对象与字符串之间存在转换(日期时间对象上的str)。例如:

>>> 'result = %s %s %s' % (datetime.now(), '>', datetime.utcfromtimestamp(41))
'result = 2011-04-07 14:13:34.819317 > 1970-01-01 00:00:41'

并且无法比较。

有人可以帮我弄这个吗?下面的工作示例:

def checkEvent( prevEvent, currentEvent, prevTime, currentTime ):

    def checkCondition( condition ):

        #condition format
        #tuple ( (oldEvent, newEvent), time, ip)
        # eg: (('co', 'co'), '>=', '!=')

        c1 = c2 = False

        #check Event
        if prevEvent == condition[0][0] and currentEvent == condition[0][1]:
            c1 = True
        else:
            return False

        #check time
        if condition[1]:
            c = condition[1]

            if c == '>' and ( prevTime > currentTime ):
                c2 = True
            elif c == '>=' and ( prevTime >= currentTime ):
                c2 = True
            elif c == '<' and ( prevTime < currentTime ):
                c2 = True
            elif c == '<=' and ( prevTime <= currentTime ):
                c2 = True
            elif c == '==' and ( prevTime == currentTime ):
                c2 = True

        else:
            c2 = True


        return c1 and c2


    def add():
        print 'add'

    def changeState():
        print 'changeState'

    def finish():
        print 'finish'

    def update():
        print 'update'    


    conditions = (\
                    ( ( ( 're', 'co' ), None ),  ( add, changeState ) ),
                    ( ( ( 'ex', 'co' ), None ),  ( add, changeState ) ),
                    ( ( ( 'co', 'co' ), '<'  ),  ( add, changeState ) ),
                    ( ( ( 'co', 'co' ), '>=' ),  ( add, changeState, finish ) ),
                    ( ( ( 'co', 'co' ), '>=' ),  ( update, ) ),
                    ( ( ( 'co', 're' ), '>=' ),  ( changeState, finish ) ),
                    ( ( ( 'co', 'ex' ), '>=' ),  ( changeState, finish ) ) 
                 )  


    for condition in conditions:
        if checkCondition( condition[0] ):
            for cmd in condition[1]:
                cmd()


from datetime import datetime

checkEvent( 'co', 'co', datetime.utcfromtimestamp(41), datetime.now() )
checkEvent( 'ex', 'co', datetime.utcfromtimestamp(41), datetime.now() )
checkEvent( 'co', 'co', datetime.utcfromtimestamp(41), datetime.utcfromtimestamp(40) )
4

4 回答 4

8

您可以尝试制作运营商地图,如下所示:

import operator

compares = {
    '>': operator.gt,
    '>=': operator.ge,
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq
}

def check(c, prev, current):
    func = compares[c]
    return func(prev, current)

print check('>', 5, 3)  # prints: True
print check('>=', 5, 5) # prints: True
print check('<', 3, 5)  # prints: True
print check('<=', 3, 3) # prints: True
print check('==', 7, 7) # prints: True
于 2011-04-07T13:07:25.097 回答
5

人们会这样做:

result= { '=': lambda a, b: a == b,
    '>': lambda a, b: a > b,
    '>=': lambda a, b: a >= b,
    etc.
    }[condition]( prevTime, currentTime )
于 2011-04-07T13:07:01.153 回答
0

您是否正在寻找类似的东西:

>>> eval('datetime.now() %s datetime.utcfromtimestamp(41)' % '>')
True

你的评估失败了,因为你在评估之外做了太多的计算。

当然,eval 策略本身是丑陋的;您应该使用其他答案之一;)

于 2011-04-07T13:10:47.863 回答
0

您仅c1 = True在函数不返回时进行设置,因此在函数结束时保证为 True。把它排除在外。

此函数的输出将是相同的:

def checkEvent( prevEvent, currentEvent, prevTime, currentTime ):

    def checkCondition( condition ):

        #condition format
        #tuple ( (oldEvent, newEvent), time, ip)
        # eg: (('co', 'co'), '>=', '!=')

        #check Event
        if not (prevEvent == condition[0][0] and currentEvent == condition[0][1]):
            return False

        #check time
        c = condition[1]
        if not condition[1]:
            return True

        if c == '>' and ( prevTime > currentTime ):
            return True
        elif c == '>=' and ( prevTime >= currentTime ):
            return True
        elif c == '<' and ( prevTime < currentTime ):
            return True
        elif c == '<=' and ( prevTime <= currentTime ):
            return True
        elif c == '==' and ( prevTime == currentTime ):
            return True

        return False

注意:其他人的“函数字典”方法是 Pythonic 的方法。我只是想展示你的原始函数的一个清理版本,它以你已经熟悉的方式工作,但流程更直接。

于 2011-04-07T13:12:14.583 回答