【问题标题】:Is there a neat way to perform XOR operation on two conditions in IF statement?是否有一种简洁的方法可以对 IF 语句中的两个条件执行 XOR 操作?
【发布时间】:2016-10-31 03:39:06
【问题描述】:

我目前正在创建一个二进制计算器,它允许正负二进制输入。关于我的问题,我有以下代码:

if (firstvalue[0] == "-" and not secondvalue[0] == "-") or (secondvalue[0] == "-" and not firstvalue[0] == "-"): 
    invertedbinary.append("-")

很明显,如果任何一个数字都是负数,但不是两者都是负数,那么最后的字符串将有一个负号。否则,两者都是正数,字符串上不会有负号。

我只是想知道是否有更简洁的方法可以做到这一点?我尝试使用^,但我猜它只是一个位运算符。

if firstvalue[0] == "-" ^ secondvalue[0] == "-":

我也尝试了xor,以防万一,但显然没有运气。关于更简洁的方法的任何建议?

【问题讨论】:

    标签: python binary logical-operators xor


    【解决方案1】:

    ^ 使用括号就可以正常工作:

    if (firstvalue[0] == "-") ^ (secondvalue[0] == "-"):
    

    您也可以使用!= 代替^。它在这里的工作方式完全相同,但可能更清楚一点。

    【讨论】:

    • 天哪,真不敢相信我错过了这么明显的东西。感谢您发现!
    【解决方案2】:

    ^ 要记住的一件事是,如果任何表达式不是布尔值,它会出现意外行为:a ^ b 不等于 (a and not b) or (b and not a),如果,比如 a = 5b = 2


    既然xor不能短路,你也可以用一个函数。

    from operator import xor as xor_
    from functools import reduce
    
    def xor(*args):
        return reduce(xor_, map(bool, args))
    
    if xor(firstvalue[0] == '-', secondvalue[0] == '-'):
        ...
    

    这适用于任意数量的值,也适用于非布尔值,因此您可以使用 xor(1, 1, 1, 1) = 0xor(1, 1, 1, 1, 1) = 1

    【讨论】:

      猜你喜欢
      • 2021-01-13
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      相关资源
      最近更新 更多