python切片赋值和bytearray的内存视图

问题描述 投票:0回答:1

抱歉,如果我的英语不好,我以韩语为母语。

我正在编写部分更改字节数组的代码。 我试图为字节数组的某些部分的内存视图命名,并用该内存视图更新字节数组。大致如下:

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。它必须是整个字节数组吗?整个内存视图?

python-3.x slice variable-assignment memoryview python-bytearray
1个回答
0
投票

如果我理解正确的话,你想要这样的东西:

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-***')
© www.soinside.com 2019 - 2024. All rights reserved.