Python `从'donds';你不能用“bytearray”吗?

Python `从'donds';你不能用“bytearray”吗?,python,binary-data,Python,Binary Data,从字符串中解包工作: >>> import struct >>> struct.unpack('>h', 'ab') (24930,) >>> struct.unpack_from('>h', 'zabx', 1) (24930,) 但是如果它是一个字节数组: >>> struct.unpack_from('>h', bytearray('zabx'), 1) Traceback (most recent

从字符串中解包工作:

>>> import struct
>>> struct.unpack('>h', 'ab')
(24930,)
>>> struct.unpack_from('>h', 'zabx', 1)
(24930,)
但是如果它是一个
字节数组

>>> struct.unpack_from('>h', bytearray('zabx'), 1)
Traceback (most recent call last):
  File "<ipython-input-4-d58338aafb82>", line 1, in <module>
    struct.unpack_from('>h', bytearray('zabx'), 1)
TypeError: unpack_from() argument 1 must be string or read-only buffer, not bytearray
但是我明确地试图避免复制可能大量的内存。

看起来
buffer()
是解决方案:

>>> struct.unpack_from('>h', buffer(bytearray('zabx')), 1)
(24930,)
buffer()
不是原件的副本,而是一个视图:

>>> b0 = bytearray('xaby')
>>> b1 = buffer(b0)
>>> b1
<read-only buffer for ...>
>>> b1[1:3]
'ab'
>>> b0[1:3] = 'nu'
>>> b1[1:3]
'nu'

您可以使用缓冲区类型引用字符串而不占用更多内存,然后将其作为参数传递。为什么不使用
buffer('xaby',index,length)
?这也不会占用额外的内存。
struct
位恰好围绕着一个
bytearray
,因为它是可变的。每次都不保留主可变数据的只读视图,而是只在中间重新创建位以从主源获取数据。这也适用于只保留
(24930,)
。我真的很想从
bytearray
@Asad中解包:我怀疑创建
缓冲区
对象至少会消耗一点内存。@TokenMacGuy我现在明白了;在最后几行中没有真正注意到bytearray的修改。
>>> b0 = bytearray('xaby')
>>> b1 = buffer(b0)
>>> b1
<read-only buffer for ...>
>>> b1[1:3]
'ab'
>>> b0[1:3] = 'nu'
>>> b1[1:3]
'nu'
Python 3.2.3 (default, Jun  8 2012, 05:36:09) 
[GCC 4.7.0 20120507 (Red Hat 4.7.0-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import struct
>>> struct.unpack_from('>h', b'xaby', 1)
(24930,)
>>> struct.unpack_from('>h', bytearray(b'xaby'), 1)
(24930,)
>>>