gpt4 book ai didi

python - 高效的字节查找表

转载 作者:行者123 更新时间:2023-12-01 01:05:44 26 4
gpt4 key购买 nike

我需要将原始字节解包为位。现在我有了原始数据和查找表。迭代输入数据以生成输出的最有效方法是什么?或者也许还有另一种方法可以做到这一点?

#Look up table looks something like this.
lookup = {
0: b'\x00\x00\x00\x00\x00\x00\x00\x00',
1: b'\x00\x00\x00\x00\x00\x00\x00\x01',
2: b'\x00\x00\x00\x00\x00\x00\x01\x00',
...
255: b'\x01\x01\x01\x01\x01\x01\x01\x01',
}

def remap(data):
out = [lookup(byte) for byte in data]
row = b''.join(out)

以下是最耗时的函数:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
44000 2.843 0.000 2.843 0.000 main.py:59(<listcomp>)
44007 0.593 0.000 0.593 0.000 {method 'join' of 'bytes' objects}

最佳答案

事实证明我的猜测是完全错误的。但这些评论对于为什么会这样有一些有趣的解读。

<小时/>

这里我给出了两个小改进,希望可以稍微提高运行时性能。

首先,您的查找表以自然数作为键。这是一个列表。

lookup = [
b'\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x01',
b'\x00\x00\x00\x00\x00\x00\x01\x00',
...
b'\x01\x01\x01\x01\x01\x01\x01\x01',
]

其次,不要构造列表然后输入它来加入,而是使用生成器

def remap(data):
return b''.join(lookup[byte] for byte in data)

但是您可能也想测试这个问题中的想法:

Converting integer to binary in python

<小时/>

也许这也符合您的需求,但它提供的是列表而不是 bstring。

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.unpackbits.html#numpy.unpackbits

关于python - 高效的字节查找表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55376411/

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