你可以做这样的事情(快速编码,可以使用一些工作)
import struct
type_map = {
'string type': 's',
'short int type': 'h',
'long int type': 'q',
'float': 'f'
}
conversion = {
's': str,
'h': int,
'q': int,
'f': float
}
def do_pack(types, data):
if len(types) != len(data):
raise Excpetion("wrong lengths")
packing = '<'
data_iter = []
for i, struct_type in enumerate(types):
t = type_map[struct_type]
if t == 's':
packing += '%ds' % len(data[i])
data_iter.append(data[i])
else:
packing += t
data_iter.append(conversion[t](data[i]))
return struct.pack(packing, *data_iter), packing
packer = [['string type','short int type','long int type','string type','float'],['Stackoverflow','32','0','any stringgg','55.0'],['anystring','16','1654657987984','striiingg','2.5']]
types = packer[0]
for data_set in packer[1:]:
binary, packing = do_pack(types, data_set)
print struct.unpack(packing, binary)
输出
('Stackoverflow', 32, 0, 'any stringgg', 55.0)
('anystring', 16, 1654657987984, 'striiingg', 2.5)