python - 包格式字符串中的自动重复标志

标签 python pack

在 php 中,unpack() 有一个“*”标志,意思是“重复这种格式直到输入结束”。例如,这将打印 97、98、99

$str = "abc";
$b = unpack("c*", $str);
print_r($b);

python中有这样的东西吗?我当然可以做

str = "abc"
print struct.unpack("b" * len(str), str)

但我想知道是否有更好的方法。

最佳答案

在 Python 3.4 及更高版本中,您可以使用新函数 struct.iter_unpack .

struct.iter_unpack(fmt, buffer)

Iteratively unpack from the buffer buffer according to the format string fmt. This function returns an iterator which will read equally-sized chunks from the buffer until all its contents have been consumed. The buffer’s size in bytes must be a multiple of the size required by the format, as reflected by calcsize().

Each iteration yields a tuple as specified by the format string.

假设我们要解压数组 b'\x01\x02\x03'*3使用重复格式字符串 '<2sc' (2 个字符后跟一个字符,重复直到完成)。

iter_unpack ,您可以执行以下操作:

>>> import struct
>>> some_bytes = b'\x01\x02\x03'*3
>>> fmt = '<2sc'
>>> 
>>> tuple(struct.iter_unpack(fmt, some_bytes))
((b'\x01\x02', b'\x03'), (b'\x01\x02', b'\x03'), (b'\x01\x02', b'\x03'))

如果你想取消嵌套这个结果,你可以使用 itertools.chain.from_iterable 来实现.

>>> from itertools import chain
>>> tuple(chain.from_iterable(struct.iter_unpack(fmt, some_bytes)))
(b'\x01\x02', b'\x03', b'\x01\x02', b'\x03', b'\x01\x02', b'\x03')

当然,您可以只使用嵌套理解来做同样的事情。

>>> tuple(x for subtuple in struct.iter_unpack(fmt, some_bytes) for x in subtuple)
(b'\x01\x02', b'\x03', b'\x01\x02', b'\x03', b'\x01\x02', b'\x03')

关于python - 包格式字符串中的自动重复标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7867714/

相关文章:

Python:如何通过网络连接传输可变长度数组

python - Writer.add_document() 函数错误 Whoosh - mysql 循环

python - 为什么最小(非贪婪)匹配会受到字符串结尾字符 '$' 的影响?

python - celery任务的实时进度跟踪

perl - 打包/解包 - little endian - 64 位 - 问题

android - 重复类 kotlin 类 kotlin 版本 1.3.70

python - 使用 keras 进行零均值卷积

python数据框根据列删除重复项

python - 在Python中打包/解包复杂数据

javascript - 为什么这会降低音频质量?