字节数组上的Python连接

2024-09-28 03:20:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要遍历一个字节数组数组,然后从字典中选择一个匹配的元素。但是,我尝试加入字节数组失败:

roms = {
  "\xff\xfe\x88\x84\x16\x03\xd1":"living_room",
  "\x10\xe5x\xd5\x01\x08\x007":"bed_room"
}

devices = [bytearray(b'(\xff\xfe\x88\x84\x16\x03\xd1'), bytearray(b'\x10\xe5x\xd5\x01\x08\x007')]
for device in devices:
  DEV = "".join(device)
  print(roms[DEV])

>> TypeError: sequence item 0: expected str instance, int found

所以看起来你不能加入一个整数,有别的方法吗?在

更新1

在@falsetrue的帮助和耐心下,我成功地加入了阵法。但是,当我尝试获取设备字典项时,结果字符串仍会抛出一个键错误:

^{pr2}$

更新2

以下是设备信息:

release='1.3.0.b1', 
version='v1.8.6-379-gc44ebac on 2017-01-13', 
machine='WiPy with ESP32'

也许其他有WIPY2的人可以帮我验证一下?


Tags: 字典字节数组roomx10x03xffroms
1条回答
网友
1楼 · 发布于 2024-09-28 03:20:15

如果您使用的是Python 3.x:

可以使用^{}(或^{})将字节解码为str

devices = [bytearray(b'\xff\xfe\x88\x84\x16\x03\xd1'),
           bytearray(b'\x10\xe5x\xd5\x01\x08\x007')]
for device in devices:
    DEV = device.decode('latin1')  # Use bytes.decode to convert to str
                                   # (or bytearray.decode)
    print(roms[DEV])

印刷品

^{pr2}$

顺便说一句,我删除了字节文字中的(。在

devices = [bytearray(b'(\xff\xfe\x88\x84\x16\x03\xd1'), ...
                       ^

更新

如果您使用的是Python 2.x:

使用bytes函数将device转换为bytes

for device in devices:
    DEV = bytes(device)
    print(roms[DEV])

相关问题 更多 >

    热门问题