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
xwere instead anumpy.arrayof bools? Is there a special command for that?
I have a large m-by-n array of booleans, where each n-element row represents a single low-dimensional hash of a high-dimensional feature vector. (In the example above, n = 4.) I would like to know the answer in order to compress my data as much as possible. Thank you.
Edit: Thank you for the responses! Using the following test code,
t = 0
for iter in range(500):
B = scipy.signbit(scipy.randn(1000,20))
for b in B:
t0 = time.clock()
# test code here
t1 = time.clock()
t += (t1-t0)
print t
...here were the runtimes on my Thinkpad laptop:
- My answer: 4.26 sec
- Sven Marnach 1: 7.88
- Emil H: 8.51
- Sven Marnach 2: 8.72
- delnan: 10.14
- liori: 53.49
Of course, I welcome any independent tests that may confirm or refute my data!
Edit: In my answer below, changing int(j) to simply j still works, but runs six times as slow! Then perhaps the other answers would become faster if the bool was casted using int. But I'm too lazy to test everything again.
Edit: liori posted results of independent tests here.
x[0]is the LSB, andx[-1]is the MSB.timeitfor testing, it is much less prone to errors. My times: pastebin.com/x1FEP9gY