How to convert ‘false’ to 0 and ‘true’ to 1 in Python

后端 未结 9 1059
情歌与酒
情歌与酒 2021-01-29 22:55

Is there a way to convert true of type unicode to 1 and false of type unicode to 0 (in Python)?

For example: x

9条回答
  •  [愿得一人]
    2021-01-29 23:19

    Here's a yet another solution to your problem:

    def to_bool(s):
        return 1 - sum(map(ord, s)) % 2
        # return 1 - sum(s.encode('ascii')) % 2  # Alternative for Python 3
    

    It works because the sum of the ASCII codes of 'true' is 448, which is even, while the sum of the ASCII codes of 'false' is 523 which is odd.


    The funny thing about this solution is that its result is pretty random if the input is not one of 'true' or 'false'. Half of the time it will return 0, and the other half 1. The variant using encode will raise an encoding error if the input is not ASCII (thus increasing the undefined-ness of the behaviour).


    Seriously, I believe the most readable, and faster, solution is to use an if:

    def to_bool(s):
        return 1 if s == 'true' else 0
    

    See some microbenchmarks:

    In [14]: def most_readable(s):
        ...:     return 1 if s == 'true' else 0
    
    In [15]: def int_cast(s):
        ...:     return int(s == 'true')
    
    In [16]: def str2bool(s):
        ...:     try:
        ...:         return ['false', 'true'].index(s)
        ...:     except (ValueError, AttributeError):
        ...:         raise ValueError()
    
    In [17]: def str2bool2(s):
        ...:     try:
        ...:         return ('false', 'true').index(s)
        ...:     except (ValueError, AttributeError):
        ...:         raise ValueError()
    
    In [18]: def to_bool(s):
        ...:     return 1 - sum(s.encode('ascii')) % 2
    
    In [19]: %timeit most_readable('true')
    10000000 loops, best of 3: 112 ns per loop
    
    In [20]: %timeit most_readable('false')
    10000000 loops, best of 3: 109 ns per loop
    
    In [21]: %timeit int_cast('true')
    1000000 loops, best of 3: 259 ns per loop
    
    In [22]: %timeit int_cast('false')
    1000000 loops, best of 3: 262 ns per loop
    
    In [23]: %timeit str2bool('true')
    1000000 loops, best of 3: 343 ns per loop
    
    In [24]: %timeit str2bool('false')
    1000000 loops, best of 3: 325 ns per loop
    
    In [25]: %timeit str2bool2('true')
    1000000 loops, best of 3: 295 ns per loop
    
    In [26]: %timeit str2bool2('false')
    1000000 loops, best of 3: 277 ns per loop
    
    In [27]: %timeit to_bool('true')
    1000000 loops, best of 3: 607 ns per loop
    
    In [28]: %timeit to_bool('false')
    1000000 loops, best of 3: 612 ns per loop
    

    Notice how the if solution is at least 2.5x times faster than all the other solutions. It does not make sense to put as a requirement to avoid using ifs except if this is some kind of homework (in which case you shouldn't have asked this in the first place).

提交回复
热议问题