Skip to main content
 首页 » 编程设计

python之组合复合条件

2025年05月04日20小虾米

我尝试重构复合条件

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

像这样的代码

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

没用。

请您参考如下方法:

所以你知道这是可行的:

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

它解析为(not (foo in categories)) and (not (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: 

请注意它并没有更短,而且更难理解。