Python XOR 首选项:按位运算符与布尔运算符 [英] Python XOR preference: bitwise operator vs. boolean operators

查看:41
本文介绍了Python XOR 首选项:按位运算符与布尔运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 中进行逻辑 XOR 是否有首选方法?

Is there a preferred method for doing a logical XOR in python?

例如,如果我有两个变量 a 和 b,并且我想检查至少一个存在但不是两个都存在,我有两种方法:

For example, if I have two variables a and b, and I want to check that at least one exists but not both, I have two methods:

方法一(按位运算符):

Method 1 (bitwise operator):

if bool(a) ^ bool(b):
    do x

方法二(布尔运算符):

Method 2 (boolean operators):

if (not a and b) or (a and not b):
    do x

使用任何一种都有固有的性能优势吗?方法 2 看起来更pythonic",但方法 1 对我来说看起来更简洁.这个相关线程似乎表明它可能取决于什么变量类型ab 排在第一位!

Is there an inherent performance benefit to using either one? Method 2 seems more "pythonic" but Method 1 looks much cleaner to me. This related thread seems to indicate that it might depend on what variable types a and b are in the first place!

任何一种方式都有强有力的论据?

Any strong arguments either way?

推荐答案

实现它的另一种方法是使用 any()all() ,例如:

One of the alternative way to achieve it is using any() and all() like:

if any([a, b]) and not all([a, b]):
    print "Either a or b is having value"

但根据性能,以下是结果:

But based on the performance, below are the results:

  1. 使用 any()all():每个循环 0.542 usec

moin@moin-pc:~$ python -m "timeit" "a='a';b='b';" "any([a, b]) and not all([a, b])"
1000000 loops, best of 3: 0.542 usec per loop

  • 使用bool(a) ^ bool(b):每个循环0.594 usec

    moin@moin-pc:~$ python -m "timeit" "a='a';b='b';" "bool(a) ^ bool(b)"
    1000000 loops, best of 3: 0.594 usec per loop
    

  • 使用(not a and b) or (a and not b):0.0988 usec per loop

    moin@moin-pc:~$ python -m "timeit" "a='a';b='b';" "(not a and b) or (a and not b)"
    10000000 loops, best of 3: 0.0988 usec per loop
    

  • 显然,您的(not a and b) or (a and not b) 效率更高.效率大约是其他人的 6 倍.

    Clearly, your (not a and b) or (a and not b) is more efficient. Approximately 6 times efficient then others.

    比较几种andor:

    1. 使用 a 而不是 b 或 b 而不是 a(正如 TemporalWolf 指出的那样):每个循环 0.116 usec

    1. Using a and not b or b and not a (as pointed by TemporalWolf): 0.116 usec per loop

    moin@moin-pc:~$ python -m "timeit" "a='a';b='b';" "a and not b or b and not a"
    10000000 loops, best of 3: 0.116 usec per loop
    

  • 使用 (a or b) 而不是 (a and b):每个循环 0.0951 usec

  • Using (a or b) and not (a and b): 0.0951 usec per loop

    moin@moin-pc:~$ python -m "timeit" "a='a';b='b';" "(a or b) and not (a and b)"
    10000000 loops, best of 3: 0.0951 usec per loop
    

  • 注意:这个性能是根据ab的值作为str来评估的,并且是依赖的关于 __nonzero__/__bool__/__or__ functions 的实现,正如 viraptor在评论中.

    Note: This performance is evaluated for the value of a and b as str, and is dependent on the implementation of __nonzero__ / __bool__ / __or__ functions as is mentioned by viraptor in comment.

    这篇关于Python XOR 首选项:按位运算符与布尔运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆