【问题标题】:allocating a bytes list in Python在 Python 中分配字节列表
【发布时间】:2021-04-28 11:34:20
【问题描述】:

我有 2 个以字节形式读取的文件,还有另一个硬编码的 64 字节数组,我需要稍后对其进行操作。

 temp_list = []
    open_file_to_list(file_name1, temp_list)
    open_file_to_list(file_name2, temp_list)
    for byte_i in harcoded_arr: #byte_i is really an int
        temp_list.append(byte_i)

为了创建硬编码数组,我使用了 bytearray,但是当我对其进行迭代时,它会以整数而不是字节的形式进行迭代。

我想将字节数组作为字节追加到列表中。

  harcoded_arr= bytearray(64)
  harcoded_arr[61] = 1
  harcoded_arr[62] = 1
  harcoded_arr[63] = 1

如何使用 Python 3.8 将 bytearray 迭代为字节

【问题讨论】:

  • 你想让harcoded_arr[63] = 1 成为bytearray(b'\x01')吗?
  • @toRex 是的,那个也是。但我希望整个数组作为字节列表。添加到其他列表

标签: arrays python-3.x list


【解决方案1】:

您可以对字节对象进行切片以获得长度为 1 的字节对象

harcoded_arr = bytearray(64)
harcoded_arr[61] = 1
harcoded_arr[62] = 1
harcoded_arr[63] = 1

for i in range(len(harcoded_arr)):
    print(harcoded_arr[i:i+1])

输出

bytearray(b'\x00')
bytearray(b'\x00')
bytearray(b'\x00')
.................
bytearray(b'\x01')
bytearray(b'\x01')
bytearray(b'\x01')

PEP-467 建议 bytes 和 bytearray 获得优化的 iterbytes 方法,该方法生成长度为 1 字节的对象而不是整数

>>> tuple(b"ABC".iterbytes())
(b'A', b'B', b'C')

更多信息你也可以通过这个answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 2021-12-27
    • 1970-01-01
    • 2015-11-23
    • 2022-01-22
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多