检查条件的更简单方法?

0 投票
4 回答
2325 浏览
提问于 2025-04-16 15:16

我刚开始学习Python,想把这个检查器简化一下。我该怎么把:

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

改成类似这样的:

 if  prevTime | condition |  currentTime:
    doSomething()

我试过使用evaluatecompile,但是在创建字符串的时候,datetime对象需要转换成字符串(就是对datetime对象使用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 个回答

0

你是不是在找类似这样的东西:

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

你的评估(eval)失败了,因为你在评估外面做了太多的计算。

当然,这种评估的方法本身就不太好;你应该看看其他的答案哦;)

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
5

大家会这样做:

result= { '=': lambda a, b: a == b,
    '>': lambda a, b: a > b,
    '>=': lambda a, b: a >= b,
    etc.
    }[condition]( prevTime, currentTime )

撰写回答