【问题标题】:Python join on byte arrayPython加入字节数组
【发布时间】:2017-05-31 23:49:04
【问题描述】:

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

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

【问题讨论】:

  • 听起来像是 X-Y 问题。正如您所展示的那样,没有理由“加入”字节数组。你甚至没有把两个结合在一起。请进一步解释。另外,roms 中的键不应该是字节字符串吗?例如:b'\xff\xfe...'。如果它们是,并且devices 也是字节字符串,那么roms[devce] 就可以工作。
  • 我不建议使用str;它将添加b'...' 并转义字节;这会使情况变得更糟;不要那样做!
  • 仅供参考,这是什么版本的Micropython——pyboard、WiPy等?
  • @nekomatic - 'WiPy', release='1.3.0.b1', version='v1.8.6-379-gc44ebac on 2017-01-13', machine='WiPy with ESP32'
  • 好的,在任何其他问题中都值得一提。与 pyboard 参考版本相比,基于 CC3200 的原始 WiPy 具有显着缩减的 MicroPython 版本,但看起来 ESP32 WiPy 更接近参考版本。

标签: python micropython


【解决方案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

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

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

【讨论】:

  • 非常感谢您的帮助,但是当我运行时,我得到:“AttributeError: 'bytearray' object has no attribute 'decode'”
  • @crankshaft, DEV = bytes(device).decode('latin1') 怎么样?
  • 取得了一些进展,该行没有错误,但是当我尝试使用 DEV 获取字典设备时,我收到另一个错误:“KeyError: (����”
  • @crankshaft,我误解你使用的是 Python 3.x。我更新了答案,请检查一下。简而言之,试试DEV = bytes(device)。 micropython 似乎没有完全实现 Python 3.x。
  • @crankshaft,正如我在答案中所写,字节数组文字中有一个额外的(。是故意的吗?
猜你喜欢
  • 2018-03-02
  • 2012-10-18
  • 1970-01-01
  • 2011-07-02
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
相关资源
最近更新 更多