1

对不起我的英语不好

我有一个类似的列表:

[['string type','short int type','long int type','string type','float'],
['Stackoverflow','32','0','any stringgg','55.0'],
['anystring','16','1654657987984','striiingg','2.5']]

我打电话:

['string type','short int type','long int type','string type','float']

是第一个子列表并且

['Stackoverflow','32','0','any stringgg','55.0']

是第二个子列表,三个子列表相同

如何根据第一个子列表的类型在第二个和第三个子列表中使用 struct.pack() 数据?

4

1 回答 1

1

你可以做这样的事情(快速编码,可以使用一些工作)

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)
于 2012-08-16T04:23:58.247 回答