Python连接字节数组

时间:2017-01-17 02:41:30

标签: python micropython

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

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的帮助和耐心下,我成功加入了阵列。但是,当我尝试获取设备字典项时,结果字符串仍然会引发键错误:

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 = str(bytes(device)).strip('b').strip("'").strip('(') # > this results in: \xff\xfe\x88\x84\x16\x03\xd1 - but still gives keyError
  #DEV = bytes(device).lstrip(b'(') # > This results in: b'\xff\xfe\x88\x84\x16\x03\xd1' - keyError
  print(DEV)
  print(roms["\xff\xfe\x88\x84\x16\x03\xd1"])
  print(roms[DEV])
  print()

>> \xff\xfe\x88\x84\x16\x03\xd1
>> living_room
>> KeyError: \xff\xfe\x88\x84\x16\x03\xd1

更新2

这是设备信息:

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

也许拥有WIPY2的其他人可以为我验证这一点?

1 个答案:

答案 0 :(得分:1)

如果你正在使用Python 3.x:

您可以使用bytes.decode(或bytearray.decode

将字节解码为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])

打印

living_room
bed_room

BTW,我在字节文字中删除了(

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

更新

如果你正在使用Python 2.x:

使用device函数将bytes转换为bytes

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