Python 检查条件的更简单方法?

Python 检查条件的更简单方法?,python,multiple-conditions,Python,Multiple Conditions,我是python新手,需要简化这个检查器。我怎样才能改变: ... if c == '>' and ( prevTime > currentTime ): c2 = True elif c == '>=' and ( prevTime >= currentTime ): c2 = True ... 例如: if prevTime | condition | currentTime: doSomething() >>> e

我是python新手,需要简化这个检查器。我怎样才能改变:

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

 if  prevTime | condition |  currentTime:
    doSomething()
>>> eval('datetime.now() %s datetime.utcfromtimestamp(41)' % '>')
True
我尝试过使用求值编译,但在创建字符串的过程中,datetime对象与字符串之间存在转换(stron datetime对象)。例如:

>>> '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) )
def checkEvent(prevEvent、currentEvent、prevTime、currentTime):
def检查条件(条件):
#条件格式
#元组((oldEvent,newEvent),时间,ip)
#例如:(('co','co'),'>=','!=')
c1=c2=False
#检查事件
如果prevEvent==条件[0][0]和currentEvent==条件[0][1]:
c1=真
其他:
返回错误
#检查时间
如果条件[1]:
c=条件[1]
如果c=='>'和(prevTime>currentTime):
c2=真
elif c=='>='和(prevTime>=currentTime):
c2=真
elif c=='='),(changeState,finish)),
((('co','ex'),'>='),(变更状态,完成))
)  
对于条件中的条件:
如果检查条件(条件[0]):
对于条件[1]中的cmd:
cmd()
从日期时间导入日期时间
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))

人们会这样做:

result= { '=': lambda a, b: a == b,
    '>': lambda a, b: a > b,
    '>=': lambda a, b: a >= b,
    etc.
    }[condition]( prevTime, currentTime )
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

您可以尝试制作操作符的映射,如下所示:

result= { '=': lambda a, b: a == b,
    '>': lambda a, b: a > b,
    '>=': lambda a, b: a >= b,
    etc.
    }[condition]( prevTime, currentTime )
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
导入操作符
比较={
“>”:operator.gt,
“>=”:operator.ge,
“=”,5,5)#打印:对

打印检查(“您是否正在寻找以下内容:

 if  prevTime | condition |  currentTime:
    doSomething()
>>> eval('datetime.now() %s datetime.utcfromtimestamp(41)' % '>')
True
你的评估失败是因为你在评估之外做了太多的计算


当然,eval策略本身很难看;您应该使用其他答案中的一个;)

如果函数没有返回,您只需要设置
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
def checkEvent(prevEvent、currentEvent、prevTime、currentTime):
def检查条件(条件):
#条件格式
#元组((oldEvent,newEvent),时间,ip)
#例如:(('co','co'),'>=','!=')
#检查事件
如果不是(prevEvent==条件[0][0]和currentEvent==条件[0][1]):
返回错误
#检查时间
c=条件[1]
如果不是条件[1]:
返回真值
如果c=='>'和(prevTime>currentTime):
返回真值
elif c=='>='和(prevTime>=currentTime):
返回真值

elif c=='+1:但是,lambda!你没有收到备忘录吗?(我也没有收到;别担心。)事实上,我已经读到BDFL不喜欢lambda的消息——它可能会被滥用。
f=lambda x:return“太懒了,无法编写def”
非常令人反感。我没有考虑使用lambdas。它看起来非常紧凑。真正的checker要大得多,不仅比较datetime,还比较IP、MAC等。我认为这是最好的解决方案。谢谢。@max:虽然它可能被滥用,但它允许您在将字符串映射到函数时有很大的灵活性。只要function非常简单。如果函数变得复杂,就没有理由只为了保留lambda而编写扭曲的代码。有时,复杂函数需要一个一流的
def
。此外,
import操作符as op
大大缩短了这一过程,并使lambda批评者感到高兴。确切地说,使用操作符或lambda的解决方案是可行的ce:)你说得对!我以前提到过,这个例子是原例子的缩短版。