我想将列表中的所有数据打包到一个缓冲区中,以便通过 UDP 套接字发送。列表比较长,因此索引列表中的每个元素是乏味的。这是我目前所拥有的:
NumElements = len(data)
buf = struct.pack('d'*NumElements,data[0],data[1],data[2],data[3],data[4])
但我想做一些更像 pythonic 的事情,如果我向列表中添加更多元素,则不需要更改调用...例如:
NumElements = len(data)
buf = struct.pack('d'*NumElements,data) # Returns error
有什么好的方法吗??
最佳答案
是的,您可以使用 *args
调用语法。
取而代之的是:
buf = struct.pack('d'*NumElements,data) # Returns error
……这样做:
buf = struct.pack('d'*NumElements, *data) # Works
参见 Unpacking Argument Lists在教程中。 (但实际上,请阅读第 4.7 节的全部内容,而不仅仅是 4.7.4 节,否则您将不知道“反向情况……”指的是什么……)简要说明:
… 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…
关于列表中单个元素的 Python struct.pack()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16368263/