Python中如何命名bytearray指定区段并通过名称更新原数据?
问题:为bytearray的特定区段命名并更新原数据
本人母语为韩语,英语水平有限,望谅解。我在编写修改bytearray的代码时,希望为bytearray的特定区段创建memoryview并命名,再通过该名称更新原bytearray,大致代码如下:
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的特定区段命名并通过该名称更新原数据?是否必须使用完整的bytearray或完整的memoryview?
解决方案
避免直接对bytearray切片创建memoryview:
binary_data[section1_start:section1_end]会生成原bytearray的切片副本,基于这个副本创建的memoryview无法关联原数据,修改操作自然不会影响原bytearray。正确实现方式:先创建整个bytearray的memoryview,再对这个全局memoryview做切片并命名。此时得到的是原memoryview的子视图,直接指向原bytearray的内存区域,修改子视图会同步更新原数据。示例代码:
section1_start, section1_end = 3, 7 section2_start, section2_end = 0, 3 binary_data = bytearray(range(8)) # 先创建覆盖整个bytearray的memoryview whole_mv = memoryview(binary_data) # 对全局memoryview做切片,得到指向特定区段的命名子视图 some_section_name_1 = whole_mv[section1_start:section1_end] some_section_name_2 = whole_mv[section2_start:section2_end] # 通过命名视图更新,会直接修改原bytearray some_section_name_1[:] = bytes([10,11,12,13]) some_section_name_2[:] = bytes([20,21,22]) print(binary_data) # 输出: bytearray(b'\x14\x15\x16\n\x0b\x0c\r\x07')不需要每次都操作完整的bytearray或全局memoryview,只要命名的视图是基于原bytearray的memoryview切片而来,就能直接修改原数据。
内容的提问来源于stack exchange,提问作者k9wan
相关产品推荐
相关产品推荐

