python list tuple 打包 解包,python struct.pack():将多个数据打包到列表或元组中...

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

x = [12974658, 638364, 53637, 63738363]

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

struct.pack('

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)

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))

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('

And i unpack them like

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

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 ?

解决方案

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("

'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值