你可以通过一次调用来做到这一点struct.unpack
,但你仍然需要自己分割结果:
import struct
data = struct.pack('<?3h3h', True, 1,2,3,4,5,6)
result = struct.unpack('<?3h3h', data)
is_enabled = result[0]
cmd_speed = result[1:4]
tach_speed = result[4:7]
print(is_enabled, cmd_speed, tach_speed)
产量
(True, (1, 2, 3), (4, 5, 6))
或者,你可以使用这个:
import struct
import itertools as IT
def unpack_formats(fmts, data):
data = iter(data)
return [struct.unpack(fmt, ''.join(IT.islice(data, struct.calcsize(fmt))))
for fmt in fmts]
data = struct.pack('<?3h3h', True, 1,2,3,4,5,6)
fmts = ('<?', '<3h', '<3h')
(is_enabled,), cmd_speed, tach_speed = unpack_formats(fmts, data)
print(is_enabled, cmd_speed, tach_speed)
产生
(True, (1, 2, 3), (4, 5, 6))
虽然unpack_formats
看起来更漂亮,但以下实际上更快(可能是因为''.join
不需要):
def unpack_formats2(fmts, data):
result = []
i = 0
for fmt in fmts:
size = struct.calcsize(fmt)
j = i+size
result.append(struct.unpack(fmt, data[i:j]))
i = j
return result
In [80]: %timeit unpack_formats(fmts, data)
100000 loops, best of 3: 3.51 us per loop
In [81]: %timeit unpack_formats2(fmts, data)
1000000 loops, best of 3: 1.61 us per loop