gpt4 book ai didi

python / NumPy : Convert list of bools to unsigned int

转载 作者:太空狗 更新时间:2023-10-29 17:39:31 25 4
gpt4 key购买 nike

  1. 最快(或最“Pythonic”)的转换方式是什么

    x = [False, False, True, True]

    进入 12? (如果有这种方法。)

  2. 如果 x 是 bool 值的 numpy.array 会怎么样?有专门的命令吗?

我有一个大型 m×n bool 数组,其中每个 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 笔记本电脑上的运行时间:

当然,我欢迎任何可能证实或反驳我的数据的独立测试!


编辑:在我下面的回答中,将 int(j) 更改为简单的 j 仍然有效,但运行速度慢了六倍!如果使用 int 转换 bool,那么其他答案可能会变得更快。但我懒得再测试一切。


编辑:liori 发布了独立测试的结果 here .

最佳答案

从其他各种答案中汲取各种想法,这是另一种方法:

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

在我的测试中,它的速度相当快——即使它像疯了似的溢出,对于大量位的 numpy 方法也是如此。我使用liori的测试模块进行测试。史蒂夫的方法,加上我建议的改变,只是快了一点点。但是,如果需要一次完成大量此类转换(并且位数不多),我敢打赌 numpy 会更快。

关于 python / NumPy : Convert list of bools to unsigned int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4065737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com