虽然您已经接受了我的其他答案,但在注意到您的评论解释说您真正想要的是使用 struct.pack() 将数据转换为二进制之后,我写了另一个可能更适合您的答案(尽管更长并且稍微复杂一点)。
import struct
class TypeConv(object):
BSA = '=' # native Byte order, standard Size, with no Alignment
def __init__(self, conv_func, fmt_chr):
self.__dict__.update(conv_func=conv_func, fmt_chr=fmt_chr)
def pack(self, data):
py_value = self.conv_func(data)
count = str(len(py_value)) if self.conv_func is str else ''
return struct.pack(self.BSA+count+self.fmt_chr, py_value)
type_conv = {'string': TypeConv(str, 's'),
'int32': TypeConv(int, 'i'),
'int64': TypeConv(long, 'q'),
'float32': TypeConv(float, 'f'),
}
array = [['string', 'int32', 'string', 'int64', 'float32', 'string', 'string'],
['any string', '19', 'any string', '198732132451654654',
'0.6', 'any string', 'any string']]
binary_values = [type_conv[type_id].pack(data)
for type_id, data in zip(array[0], array[1])
if type_id in type_conv] # to skip any unknown type_ids
print binary_values
输出:
['any string', '\x13\x00\x00\x00', 'any string', '\xfe\x9b<P\xd2\t\xc2\x02',
'\x9a\x99\x19?', 'any string', 'any string']
TypeConv.pack() 方法首先将字符串值转换为其等效的 Python 值 py_value,然后使用 struct.pack() 将其转换为 C 二进制值——我认为这正是您所寻求的。