Python中boolean’和’,’或’的运算符方法是什么?
发布时间:2020-12-20 13:00:53 所属栏目:Python 来源:网络整理
导读:例如,这些在 operator module中定义,可以这样使用: import operatorprint operator.__add__ # alias add - +print operator.__sub__ # alias sub - -print operator.__and__ # alias and_ - print operator.__or__ # alias or_ - | 然后是什么和和或? prin
例如,这些在
operator module中定义,可以这样使用:
import operator print operator.__add__ # alias add -> + print operator.__sub__ # alias sub -> - print operator.__and__ # alias and_ -> & print operator.__or__ # alias or_ -> | 然后是什么和和或? print operator."and ?????" # should be boolean-and print operator."or ????" # should be boolean-or 解决方法
这些不存在.你能做的最好的事就是用lambda代替它们:
band = (lambda x,y: x and y) bor = (lambda x,y: x or y) 原因是你无法实现和/或因为它们可以短路的完整行为. 例如: if variable or long_fonction_to_execute(): # do stuff 如果变量为True,则永远不会调用long_fonction_to_execute,因为Python知道或者必须返回True.这是一个优化.在大多数情况下,这是一个非常理想的功能,因为它可以节省大量无用的处理. 但这意味着你不能使它成为一个功能: 例如: if bor(variable,long_fonction_to_execute()): # do stuff 在这种情况下,甚至在评估之前就会调用long_fonction_to_execute. 幸运的是,鉴于您使用生成器和列表推导这一事实,您很少需要类似的东西. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |