1

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

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 的其他人可以为我验证这一点?

4

1 回答 1

1

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

bytes.decode您可以使用(or 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

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

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

更新

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

转换devicebytesusingbytes函数:

for device in devices:
    DEV = bytes(device)
    print(roms[DEV])
于 2017-01-17T02:54:01.067 回答