Python struct.pack() 用于列表中的单个元素?元素、列表中、Python、struct

2023-09-07 13:32:55 作者:负我狗@

我想将列表中的所有数据打包到一个缓冲区中,以通过 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

有什么好的方法吗??

推荐答案

是的,你可以使用 *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:

...当参数已经在列表或元组中但需要为需要单独的位置参数的函数调用解包时...使用 *-operator 编写函数调用以将参数从列表或元组中解包...

… when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments… write the function call with the *-operator to unpack the arguments out of a list or tuple…