When iterating over a bytes
object in Python 3, one gets the individual bytes
as ints
:
当在python3中迭代一个字节对象时,一个人会得到每个字节作为ints:
>>> [b for b in b'123']
[49, 50, 51]
How to get 1-length bytes
objects instead?
如何获得1长度的字节对象?
The following is possible, but not very obvious for the reader and most likely performs bad:
以下是可能的,但对读者来说不是很明显,而且很可能表现不好:
>>> [bytes([b]) for b in b'123']
[b'1', b'2', b'3']
2 个解决方案
#1
19
If you are concerned about performance of this code and an int
as a byte is not suitable interface in your case then you should probably reconsider data structures that you use e.g., use str
objects instead.
如果您关心这个代码的性能,而int作为一个字节并不适合您的情况,那么您应该重新考虑您使用的数据结构,例如,使用str对象。
You could slice the bytes
object to get 1-length bytes
objects:
你可以将bytes对象分割成1长度的bytes对象:
L = [bytes_obj[i:i+1] for i in range(len(bytes_obj))]
There is PEP 0467 -- Minor API improvements for binary sequences that proposes bytes.iterbytes()
method:
有PEP 0467——对二进制序列进行了少量的API改进,它提出了bytes.iterbytes()方法:
>>> list(b'123'.iterbytes())
[b'1', b'2', b'3']
#2
1
I wonder whether an array object would suit your purposes better and avoid unnecessary conversions.
我想知道数组对象是否更适合您的目的,并避免不必要的转换。
#1
19
If you are concerned about performance of this code and an int
as a byte is not suitable interface in your case then you should probably reconsider data structures that you use e.g., use str
objects instead.
如果您关心这个代码的性能,而int作为一个字节并不适合您的情况,那么您应该重新考虑您使用的数据结构,例如,使用str对象。
You could slice the bytes
object to get 1-length bytes
objects:
你可以将bytes对象分割成1长度的bytes对象:
L = [bytes_obj[i:i+1] for i in range(len(bytes_obj))]
There is PEP 0467 -- Minor API improvements for binary sequences that proposes bytes.iterbytes()
method:
有PEP 0467——对二进制序列进行了少量的API改进,它提出了bytes.iterbytes()方法:
>>> list(b'123'.iterbytes())
[b'1', b'2', b'3']
#2
1
I wonder whether an array object would suit your purposes better and avoid unnecessary conversions.
我想知道数组对象是否更适合您的目的,并避免不必要的转换。