结合复合条件

时间:2017-10-31 07:11:57

标签: python

我试图重构复合条件

if not foo in categories and not foo.capitalize() in categories:

代码

if not foo and foo.capitalize() in categories:

它不起作用。

4 个答案:

答案 0 :(得分:4)

所以你知道这有效:

if not foo in categories and not foo.capitalize() in categories:

它解析为(not (foo in categories)) and (not (foo.capitalize() in categories),即

  • foo不在类别中,
  • foo.capitalize()不在类别中。

由于解析始终以相同的方式工作,并且不会猜测您最有可能的意思,因此修改后的声明

if not foo and foo.capitalize() in categories:

被解析为(not foo) and (foo.capitalize() in categories),即

  • foo不是,
  • foo.capitalize()属于类别

在Python中编写此代码的更简洁方法是使用x not in y代替not x in y(它们是等效的):

if foo not in categories and foo.capitalize() not in categories:

但至于在这里短暂地表达“这两者”......除了集合运算符之外没有多少:

if not {foo, foo.capitalize()}.intersection(categories):

如果categories也是一个集合的简写:

if not {foo, foo.capitalize()} & categories:

请注意它是如何缩短的,以及 更难理解的方式。

答案 1 :(得分:1)

在原始if声明中,您检查了两个条件:

  1. not foo in categories - 如果在True
  2. 集合中未提供元素foostr,我将会评估为categories
  3. not foo.capitalize() in categories - 如果大写元素True未在集合foo
  4. 中显示,则会评估为categories

    在修改后的if语句中,您检查两个完全不同的条件:

    1. not foo - 如果foo为空,FalseNone
    2. ,则会评估为True
    3. foo.capitalize() in categories - 如果在集合True
    4. 中大写元素foo 呈现,则会评估为categories

答案 2 :(得分:0)

您正在做的是检查foo False是否foo.capitalize()categories.是否在<!-- this filters out the operations of your API --> <property expression="json-eval($.operation)" name="operation" /> <filter regex="menu" source="$ctx:operation"> <header description="SOAPAction" name="SOAPAction" scope="transport" value="http://ws.cdyne.com/PhoneVerify/query/CheckPhoneNumber"/> <!-- We are storing the input values which the end users input for these values into properties --> <property name="uri.var.phoneNumber" expression="$url:PhoneNumber"/> <property name="uri.var.licenseKey" expression="$url:LicenseKey"/> <!-- Since we do not want the URL pattern we mentioned to be sent to the backend we need to add the below property to remove it --> <property name="REST_URL_POSTFIX" scope="axis2" action="remove"/> <!-- Now we need to create the actual payload which the backend requires. For that we use the payload factory mediator --> <payloadFactory description="transform" media-type="xml"> <format> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:quer="http://ws.cdyne.com/PhoneVerify/query"> <soapenv:Header/> <soapenv:Body> <quer:CheckPhoneNumber> <quer:PhoneNumber>$1</quer:PhoneNumber> <quer:LicenseKey>$2</quer:LicenseKey> </quer:CheckPhoneNumber></soapenv:Body> </soapenv:Envelope> </format> <args> <arg expression="get-property(‘uri.var.phoneNumber’)"/> <arg expression="get-property(‘uri.var.licenseKey’)"/> </args> </payloadFactory>

答案 3 :(得分:0)

如果您有如上所述的具体all and / not / or个案,我通常会这样:

if not all( [foo in categories, foo.capitalize() in categories] ):

它使可读性变得简单,调试也很简单

see this thread for example