python struct.pack():将多个数据打包到列表或元组中 [英] python struct.pack(): pack multiple datas in a list or a tuple
问题描述
说我有一个list
或tuple
包含类型为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
语句内的list
或tuple
中插入项目.我试过像这样使用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
语句中直接指向list
或tuple
,还是可能使用一个衬线?
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屋!