我尝试在开始时将一个字节数组插入到另一个字节数组中。这里有一个简单的例子来说明我想要实现的目标。
import struct
a = bytearray(struct.pack(">i", 1))
b = bytearray(struct.pack(">i", 2))
a = a.insert(0, b)
print(a)但是,此操作将失败,并显示以下错误:
a = a.insert(0, b) TypeError: an integer is required
发布于 2017-09-21 04:34:46
bytearray是序列类型,它支持基于切片的操作。带有切片的"insert at position i“习惯用法是这样的x[i:i] = <a compatible sequence>。因此,对于第一个位置:
>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[0:0] = b
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x00\x00\x01')对于第三个位置:
>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[2:2] = b
>>> a
bytearray(b'\x00\x00\x00\x00\x00\x02\x00\x01')注意,这并不等同于.insert,因为对于序列,.insert插入整个对象作为第i个元素。因此,考虑下面这个简单的列表示例:
>>> y = ['a','b']
>>> x.insert(0, y)
>>>
>>> x
[['a', 'b'], 1, 2, 3]你真正想要的是:
>>> x
[1, 2, 3]
>>> y
['a', 'b']
>>> x[0:0] = y
>>> x
['a', 'b', 1, 2, 3]发布于 2017-09-21 04:33:50
>>> a = bytearray(struct.pack(">i", 1))
>>> b = bytearray(struct.pack(">i", 2))
>>> a = b + a
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x00\x00\x01')发布于 2017-09-21 06:06:34
字节数组是单字节(整数)的可变序列,因此Bytearray只接受满足值限制0 <= x <= 255的整数:
>>> a = bytearray(struct.pack(">i", 1))
>>> b = bytearray(struct.pack(">i", 2))
>>> a.insert(0,b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> a=b+a
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x00\x00\x01')
>>>a[:2]=b
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x01')https://stackoverflow.com/questions/46331220
复制相似问题