Bool array of integers

Is there a built-in function in python to convert a bool array (which represents a bit in a byte) as follows:

p = [True, True, True, False, True, False, False, True]

into a byte array like this:

bp = byteArray([233])

I know oh numpy, but I was looking for something inside python itself

+4
source share
5 answers

This will do what you want:

sum(v<<i for i, v in enumerate(p[::-1]))
+6
source

Just use algebra:

sum(2**i for i, v in enumerate(reversed(p)) if v)
+4
source

, int() .

>>> int(''.join('1' if i else '0' for i in p), 2)
233

([1 if i else 0 for i in p]) , map (map(int, p)) !

+2

int, int ( 2):

>>> p = [True, True, True, False, True, False, False, True]
>>> int(''.join(map(str, map(int, p))), 2)
233
+1
>>> p = [True, True, True, False, True, False, False, True]
>>> int("".join(map(lambda x: x and '1' or '0',p)),2)
233

int 2

0

All Articles