python struct.pack():将多个数据打包到列表或元组中 [英] python struct.pack(): pack multiple datas in a list or a tuple

查看:2025
本文介绍了python struct.pack():将多个数据打包到列表或元组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个listtuple包含类型为long long的数字​​,

Say i have a list or a tuple containing numbers of type long long,

x = [12974658, 638364, 53637, 63738363]

如果要单独struct.pack它们,我必须使用

If want to struct.pack them individually, i have to use

struct.pack('<Q', 12974658)

或者如果我想做多次,那么我必须像这样明确地提及它

or if i want to do it as multiple, then i have to explicitly mention it like this

struct.pack('<4Q', 12974658, 638364, 53637, 63738363)

但是,如何在struct.pack语句内的listtuple中插入项目.我试过像这样使用for循环.

But, how can i insert items in a list or tuple inside a struct.pack statement. I tried using for loop like this.

struct.pack('<4Q', ','.join(i for i in x))

得到错误提示expected string, int found,所以我将包含int类型的列表转换为str,现在打包它们变得更加复杂.因为整个列表都被转换为字符串(如单个句子).

got error saying expected string, int found, so i converted the list containing type int into str, now it gets much more complicated to pack them. Because the whole list gets converted into a string( like a single sentence).

截至目前,我正在做类似

As of now im doing some thing like

binary_data = ''
x = [12974658, 638364, 53637, 63738363]
for i in x:
    binary_data += struct.pack('<Q', i)

我像

struct.unpack('<4Q', binary_data)

我的问题:有没有更好的方法,例如我可以在struct.pack语句中直接指向listtuple,还是可能使用一个衬线?

My question: is there a better way around, like can i directly point a list or tuple inside the struct.pack statement, or probably a one liner ?

推荐答案

您可以 splat ,很抱歉打开参数列表":

You can splat, I'm sorry "unpack the argument list":

>>> struct.pack("<4Q", *[1,2,3,4])
'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00'

如果列表的长度是动态的,那么您当然也可以在运行时构建格式字符串:

If the length of the list is dynamic, you can of course build the format string at runtime too:

>>> x = [1, 2] # This could be any list of integers, of course.
>>> struct.pack("<%uQ" % len(x), *x)
'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00'

这篇关于python struct.pack():将多个数据打包到列表或元组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆