【问题标题】:Pythonic way of making xor test [closed]进行异或测试的Pythonic方法[关闭]
【发布时间】:2014-12-30 02:45:32
【问题描述】:

什么是pythonic方法来编写检查两个变量不能为none的条件,并且两个变量也不能不是none。例如

if a is None and b is None: raise SystemExit(1)
if a is not None and b is not None: raise SystemExit(1)
# rest of the code

【问题讨论】:

  • 您在此处使用pass 是因为您有else 声明吗?在这种情况下,为什么不使用if a is None or b is None: 进行相反的测试呢?
  • @yayu:那么你的测试不正确。你会使用if a is None and b is None: raise Exception
  • @yayu:然后把这部分作为你的问题。就目前而言,以任何有意义的方式回答都太模糊了,并且有可能被关闭为“不清楚”、“过于宽泛”或“主要基于意见”。
  • 现在是How do you get the logical xor of two variables in Python?的副本;您可以使用bool(a is None) != bool(b is None)bool(a is None) ^ bool(b is None)

标签: python


【解决方案1】:

你可以试试if all((a,b is not None)): pass

In [31]: a = 1

In [32]: b = 1

In [33]: all((a,b is not None))
Out[33]: True

In [34]: b = None

In [35]: all((a,b is not None))
Out[35]: False

注意:ab 的值设置为0 将产生True

Python 风格?

In [36]: len('if a is not None and b is not None')
Out[36]: 34

In [37]: len('all((a,b is not None))')
Out[37]: 22

【讨论】:

  • OP 想要一个 XOR 测试,例如其中一个必须None,另一个不得None
  • @MartijnPieters:你很好地理解了这个问题吗? OP说that checks that both variables cannot be none, and both variables also cannot be not None
  • 现在的问题比一开始要清楚得多,但请阅读帖子上的 cmets。 OP 要求进行 XOR 操作。
  • 我认为他编辑了这个问题。这不是他最初要求的。
  • 你只是在测试两个变量是否都是None,而不是相反的。
【解决方案2】:
if (a is None) != (b is None):
    raise SystemExit("kkthxbye")
# remainder of code

What's the difference between XOR and NOT-EQUAL-TO?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    相关资源
    最近更新 更多