在 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/