Skip to content Skip to sidebar Skip to footer

Python/numpy: Convert List Of Bools To Unsigned Int

What is the fastest (or most 'Pythonic') way to convert x = [False, False, True, True] into 12? (If there is such a way.) What if x were instead a numpy.array of bools? Is there

Solution 1:

Taking various ideas from various other answers, here's another way to do it:

sum(1<<i for i, b in enumerate(x) if b)

It is quite fast in my tests - right up with the numpy method for large number of bits even though it overflows like crazy. I used liori's testing module for testing. Steve's method, with the change I suggested, is just barely faster. However, if a lot of these sorts of conversions need to be done at a time (and with not too many bits), I'm betting that numpy will be faster.

Solution 2:

Most Pythonic might be this:

sum(2**i*b for i, b in enumerate(x))

It's hard to tell if it is also the fastest.

In numpy I would use

numpy.sum(2**numpy.arange(len(x))*x)

but this won't be faster for small arrays x, and it won't work for big arrays x since machine size integers are used instead of Pythons arbitrary precision ints.

Solution 3:

reduce(lambda a,b:2*a+b, reversed(x))

You could get rid of reversed() if you had least significant bit at the end of array. This works with numpy.array too, and doesn't need enumerate(). From my tests seem to be faster too: no need to use exponentiation.

Solution 4:

My initial attempt, just for reference:

def bool2int(x):
    y =0for i,j in enumerate(x):
        if j: y +=int(j)<<i
    return y

Solution 5:

Something like this?

>>>x = [False, False, True, True]>>>sum([int(y[1])*2**y[0] for y inenumerate(x)])
12

You can convert a numpy array to a regular list using a list() cast.

>>>a = numpy.array([1,2,3,4])>>>a
array([1, 2, 3, 4])
>>>list(a)
[1, 2, 3, 4]

Post a Comment for "Python/numpy: Convert List Of Bools To Unsigned Int"