我试图重构复合条件
if not foo in categories and not foo.capitalize() in categories:
代码
if not foo and foo.capitalize() in categories:
它不起作用。
答案 0 :(得分:4)
所以你知道这有效:
if not foo in categories and not foo.capitalize() in categories:
它解析为(not (foo in categories)) and (not (foo.capitalize() in categories)
,即
由于解析始终以相同的方式工作,并且不会猜测您最有可能的意思,因此修改后的声明
if not foo and foo.capitalize() in categories:
被解析为(not foo) and (foo.capitalize() in categories)
,即
在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
声明中,您检查了两个条件:
not foo in categories
- 如果在True
foo
(str
,我将会评估为categories
not foo.capitalize() in categories
- 如果大写元素True
未在集合foo
categories
醇>
在修改后的if
语句中,您检查两个完全不同的条件:
not foo
- 如果foo
为空,False
或None
foo.capitalize() in categories
- 如果在集合True
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] ):
它使可读性变得简单,调试也很简单