用法:
cast(format[, shape])
將內存視圖轉換為新格式或形狀。
shape
默認為[byte_length//new_itemsize]
,這意味著結果視圖將是一維的。返回值是一個新的內存視圖,但緩衝區本身並沒有被複製。支持的轉換為 1D -> C-contiguous 和 C-contiguous -> 1D。目標格式僅限於
struct
語法中的單元素本機格式。其中一種格式必須是字節格式(‘B’,‘b’ or ‘c’)。結果的字節長度必須與原始長度相同。將 1D/long 轉換為 1D/無符號字節:
>>> import array >>> a = array.array('l', [1,2,3]) >>> x = memoryview(a) >>> x.format 'l' >>> x.itemsize 8 >>> len(x) 3 >>> x.nbytes 24 >>> y = x.cast('B') >>> y.format 'B' >>> y.itemsize 1 >>> len(y) 24 >>> y.nbytes 24
將一維/無符號字節轉換為一維/字符:
>>> b = bytearray(b'zyz') >>> x = memoryview(b) >>> x[0] = b'a' Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: memoryview: invalid value for format "B" >>> y = x.cast('c') >>> y[0] = b'a' >>> b bytearray(b'ayz')
將 1D/bytes 轉換為 3D/ints 轉換為 1D/signed char:
>>> import struct >>> buf = struct.pack("i"*12, *list(range(12))) >>> x = memoryview(buf) >>> y = x.cast('i', shape=[2,2,3]) >>> y.tolist() [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] >>> y.format 'i' >>> y.itemsize 4 >>> len(y) 2 >>> y.nbytes 48 >>> z = y.cast('b') >>> z.format 'b' >>> z.itemsize 1 >>> len(z) 48 >>> z.nbytes 48
將 1D/unsigned long 轉換為 2D/unsigned long:
>>> buf = struct.pack("L"*6, *list(range(6))) >>> x = memoryview(buf) >>> y = x.cast('L', shape=[2,3]) >>> len(y) 2 >>> y.nbytes 48 >>> y.tolist() [[0, 1, 2], [3, 4, 5]]
3.3 版中的新函數。
在 3.5 版中更改:轉換為字節視圖時,源格式不再受到限製。
相關用法
- Python memoryview.itemsize用法及代碼示例
- Python memoryview.nbytes用法及代碼示例
- Python memoryview.obj用法及代碼示例
- Python memoryview.hex用法及代碼示例
- Python memoryview.toreadonly用法及代碼示例
- Python memoryview.release用法及代碼示例
- Python memoryview.tolist用法及代碼示例
- Python memoryview.__eq__用法及代碼示例
- Python memoryview.tobytes用法及代碼示例
- Python memoryview()用法及代碼示例
- Python memoryview用法及代碼示例
- Python statistics median_high()用法及代碼示例
- Python statistics median_low()用法及代碼示例
- Python statistics median()用法及代碼示例
- Python statistics median_grouped()用法及代碼示例
- Python numpy ma.MaskedArray.view用法及代碼示例
- Python matplotlib.patches.Rectangle用法及代碼示例
- Python matplotlib.pyplot.step()用法及代碼示例
- Python math.cos()用法及代碼示例
- Python math.cosh()用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 memoryview.cast。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。