在 Python 3 中迭代单个字节 [英] Iterate over individual bytes in Python 3

查看:46
本文介绍了在 Python 3 中迭代单个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 3 中迭代 bytes 对象时,将单个 bytes 获取为 ints:

<预><代码>>>>[b for b in b'123'][49, 50, 51]

如何获取长度为 1 的 bytes 对象?

以下是可能的,但对读者来说不是很明显,而且很可能表现不佳:

<预><代码>>>>[bytes([b]) for b in b'123'][b'1', b'2', b'3']

解决方案

如果您担心此代码的性能,并且 int 作为字节在您的情况下不适合接口,那么您可能应该重新考虑您使用的数据结构,例如,改用 str 对象.

您可以将 bytes 对象切片以获得 1 长度的 bytes 对象:

L = [bytes_obj[i:i+1] for i in range(len(bytes_obj))]

PEP 0467 -- 二进制序列的小幅 API 改进建议 bytes.iterbytes() 方法:

<预><代码>>>>列表(b'123'.iterbytes())[b'1', b'2', b'3']

When iterating over a bytes object in Python 3, one gets the individual bytes as ints:

>>> [b for b in b'123']
[49, 50, 51]

How to get 1-length bytes objects instead?

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']

解决方案

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.

You could slice the bytes object to get 1-length bytes objects:

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:

>>> list(b'123'.iterbytes())
[b'1', b'2', b'3']

这篇关于在 Python 3 中迭代单个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆