1

Sorry for my english

I have a list like:

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

I call:

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

is the first sub-list and

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

is the second sub-list, same for the three sub-list

How can I use struct.pack() data in the second & third sub-lists based on the type of the first sub-list?

1 Answer 1

1

You could do something like this (quickly coded, could use some work)

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)

OUTPUT

('Stackoverflow', 32, 0, 'any stringgg', 55.0)
('anystring', 16, 1654657987984, 'striiingg', 2.5)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.