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 anumpy.array
of bools? Is there a special command for that?
我有一个大的m×n布尔数组,每个n元素行表示高维特征向量的单个低维哈希。 (在上面的示例中,n = 4。)我想知道答案,以便尽可能压缩我的数据。谢谢。
编辑:感谢回复!使用以下测试代码,
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
以下是在我的Thinkpad笔记本电脑上的运行时间:
- 我的回答:4.26秒
- Sven Marnach 1:7.88秒
- Emil H:8.51秒
- Sven Marnach 2:8.72秒
- delnan:10.14秒
- liori:53.49秒
当然,我欢迎任何独立测试来证实或否认我的数据!
编辑:在下面的回答中,将int(j)
更改为简单的j
仍然有效,但运行速度慢了六倍!那么,如果使用int
来转换bool值,也许其他答案会变得更快。但我太懒了,不想再测试一遍。
编辑:liori在这里发布了独立测试结果。
timeit
进行测试,它更不容易出错。我的时间:http://pastebin.com/x1FEP9gY - liori