arv*_*ndh 3 python struct list
假设我有一个list
或tuple
包含数字的类型long long
,
x = [12974658, 638364, 53637, 63738363]
Run Code Online (Sandbox Code Playgroud)
如果想struct.pack
单独使用它们,我必须使用
struct.pack('<Q', 12974658)
Run Code Online (Sandbox Code Playgroud)
或者如果我想做多个,那么我必须像这样明确地提到它
struct.pack('<4Q', 12974658, 638364, 53637, 63738363)
Run Code Online (Sandbox Code Playgroud)
但是,我如何在声明中list
或tuple
内部插入项目struct.pack
.我尝试使用这样的for
循环.
struct.pack('<4Q', ','.join(i for i in x))
Run Code Online (Sandbox Code Playgroud)
得到错误说expected string, int found
,所以我将包含类型的列表转换int
为str
,现在包装它们变得复杂得多.因为整个列表被转换为字符串(就像一个句子).
截至目前我正在做一些事情
binary_data = ''
x = [12974658, 638364, 53637, 63738363]
for i in x:
binary_data += struct.pack('<Q', i)
Run Code Online (Sandbox Code Playgroud)
我打开包装就像
struct.unpack('<4Q', binary_data)
Run Code Online (Sandbox Code Playgroud)
我的问题:有没有更好的方法,比如我可以直接指出list
或tuple
在struct.pack
声明中,或者可能是一个班轮?
你可以splat,对不起"解压参数列表":
>>> 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'
Run Code Online (Sandbox Code Playgroud)
如果列表的长度是动态的,您当然也可以在运行时构建格式字符串:
>>> 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'
Run Code Online (Sandbox Code Playgroud)