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() 用于列表中的单个元素?
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
