python切片赋值和bytearray的memoryview

cngwdvgl  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(149)

对不起,如果我的英语不好,我说韩语作为母语。
我写的代码部分改变了字节数组。我想做的是给字节数组的某些部分的内存视图起给予名字,然后用这个内存视图更新字节数组。大致如下:

some_section_name_1 = memoryview(binary_data[section1_start:section1_end])
some_section_name_2 = memoryview(binary_data[section2_start:section2_end])

#update
some_section_name_1[:] = byte_like_object
some_section_name_2[:] = byte_like_object

但失败了所以我写了下面的代码来检查:

section1_start, section1_end = 3, 7

binary_data = bytearray(range(8))
some_section_name_1 = memoryview(binary_data[section1_start:section1_end])
some_section_name_1[:] = bytes(range(4))
print(binary_data)

binary_data = bytearray(range(8))
whole_mv = memoryview(binary_data)
whole_mv[section1_start:section1_end] = bytes(range(4))
print(binary_data)

binary_data = bytearray(range(8))
binary_data[section1_start:section1_end] = bytes(range(4))
print(binary_data)

然后我终于想起了切片会做浅拷贝,所以切片赋值只会应用于被拷贝的对象,而不是原始对象。
那么,有什么办法可以达到我原本的目的呢?命名bytearray的某些特定部分,并使用该名称更新bytearray。必须是整个字节数组吗|整个记忆视图?

klr1opcd

klr1opcd1#

如果我没理解错的话,你想要的是:

view = memoryview(binary_data)
# the following slicing operations are constant time/space!
section1 = view[section1_start:section1_end]
section2 = view[section2_start:section2_end]

some_section_name_1[:] = byte_like_object
some_section_name_2[:] = byte_like_object

你是对的,一旦你切片字节数组,它就创建了一个新的字节数组。你需要对内存视图进行切片。
举个例子:

>>> binary_data = bytearray(b"foo-bar-baz")
>>> view = memoryview(binary_data)
>>> section1 = view[:3]
>>> section2 = view[-3:]
>>> binary_data
bytearray(b'foo-bar-baz')
>>> section1[:] = b"###"
>>> section2[:] = b"***"
>>> binary_data
bytearray(b'###-bar-***')

相关问题