Python struct.pack()用于列表中的单个元素? [英] Python struct.pack() for individual elements in a list?

查看:267
本文介绍了Python struct.pack()用于列表中的单个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表中的所有数据打包到单个缓冲区中,以通过UDP套接字发送.该列表相对较长,因此对列表中的每个元素进行索引都是很繁琐的.这是我到目前为止的内容:

I would like to pack all the data in a list into a single buffer to send over a UDP socket. The list is relatively long, so indexing each element in the list is tedious. This is what I have so far:

NumElements = len(data)
buf = struct.pack('d'*NumElements,data[0],data[1],data[2],data[3],data[4])

但是我想做更多的pythonic操作,如果我在列表中添加了更多元素,则不需要更改调用...

But I would like to do something more pythonic that doesn't require I change the call if I added more elements to the list... something like:

NumElements = len(data)
buf = struct.pack('d'*NumElements,data)  # Returns error

是否有一个很好的方法?

Is there a good way of doing this??

推荐答案

是的,您可以使用*args调用语法.

Yes, you can use the *args calling syntax.

代替此:

buf = struct.pack('d'*NumElements,data)  # Returns error

…执行此操作:

buf = struct.pack('d'*NumElements, *data) # Works

请参见本教程中的解包参数列表. (但是,实际上,请阅读第4.7节的全部内容,而不仅是4.7.4,否则您将不知道相反的情况……"指的是……)简要地:

See Unpacking Argument Lists in the tutorial. (But really, read all of section 4.7, not just 4.7.4, or you won't know what "The reverse situation…" is referring to…) Briefly:

…当参数已经在列表或元组中但需要为需要单独的位置参数的函数调用而解压缩时…用*运算符编写函数调用,以将参数从列表或元组中解压缩……

这篇关于Python struct.pack()用于列表中的单个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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