0

我想分配一个大的字节数组,但也将它分成许多较小的类似字节数组的对象。当较小的对象被修改时,它们应该修改底层的字节数组。

我尝试了以下两种策略。

from pprint import pprint as pp
b = bytearray(10)
c = b[5:]
c = bytearray(1 for d in c)
pp(c)
pp(b)

from pprint import pprint as pp
b = bytearray(10)
c = b[5:]
for i in range(len(c)):
  c[i] = 1
pp(c)
pp(b)

他们都输出

bytearray(b'\x01\x01\x01\x01\x01')
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

我的目标是有一段类似的代码,它输出

bytearray(b'\x01\x01\x01\x01\x01')
bytearray(b'\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01')

即当c被更新时,b也在适当的位置被更新。

4

1 回答 1

2

memoryview接近你想要的

>>> b = bytearray(10)
>>> c = memoryview(b)[5:]
>>> c[:] = bytearray(1 for d in c)
>>> b
bytearray(b'\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01')

你必须使用c.tobytes()或传递c给 bytearray 才能看到它的内容

>>> c.tobytes()
'\x01\x01\x01\x01\x01'
>>> bytearray(c)
bytearray(b'\x01\x01\x01\x01\x01')
于 2012-09-20T07:39:14.217 回答