Python struct.pack() for individual elements in a list?(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
有什么好的方法吗??
推荐答案
是的,你可以使用 *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…
这篇关于Python struct.pack() 用于列表中的单个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python struct.pack() 用于列表中的单个元素?


基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 包装空间模型 2022-01-01