array --- 効率的な数値配列


This module defines an object type which can compactly represent an array ofbasic values: characters, integers, floating-point numbers. Arrays are sequencetypes and behave very much like lists, except that the type of objects stored inthem is constrained. The type is specified at object creation time by using atype code, which is a single character. The following type codes aredefined:

型コード

C の型

Python の型

最小サイズ (バイト単位)

注釈

'b'

signed char

int

1

'B'

unsigned char

int

1

'u'

wchar_t

Unicode文字(unicode型)

2

(1)

'w'

Py_UCS4

Unicode文字(unicode型)

4

'h'

signed short

int

2

'H'

unsigned short

int

2

'i'

signed int

int

2

'I'

unsigned int

int

2

'l'

signed long

int

4

'L'

unsigned long

int

4

'q'

signed long long

int

8

'Q'

unsigned long long

int

8

'f'

浮動小数点数

浮動小数点数

4

'd'

double

浮動小数点数

8

注釈:

  1. Це може бути 16 або 32 біти залежно від платформи.

    バージョン 3.9 で変更:array('u') now useswchar_t as C type instead of deprecatedPy_UNICODE. This change doesn't affect its behavior becausePy_UNICODE is alias ofwchar_t since Python 3.3.

    Deprecated since version 3.3, will be removed in version 3.16:Please migrate to'w' typecode.

値の実際の表現はマシンアーキテクチャ (厳密に言うとCの実装) によって決まります。値の実際のサイズはarray.itemsize 属性から得られます。

このモジュールは以下の項目を定義しています:

array.typecodes

すべての利用可能なタイプコードを含む文字列

このモジュールでは次の型を定義しています:

classarray.array(typecode[,initializer])

A new array whose items are restricted bytypecode, and initializedfrom the optionalinitializer value, which must be abytesorbytearray object, a Unicode string, or iterable over elementsof the appropriate type.

If given abytes orbytearray object, the initializeris passed to the new array'sfrombytes() method;if given a Unicode string, the initializer is passed to thefromunicode() method;otherwise, the initializer's iterator is passed to theextend() methodto add initial items to the array.

アレイオブジェクトでは、インデクス指定、スライス、連結および反復といった、 通常のシーケンスの演算をサポートしています。スライス代入を使うときは、 代入値は同じ型コードのアレイオブジェクトでなければなりません。 それ以外のオブジェクトを指定するとTypeError を送出します。 アレイオブジェクトはバッファインターフェースを実装しており、bytes-like objects をサポートしている場所ならどこでも利用できます。

引数typecode,initializer 付きで監査イベントarray.__new__ を送出します。

typecode

アレイを作るときに使う型コード文字です。

itemsize

アレイの要素 1 つの内部表現に使われるバイト長です。

append(x)

x の新たな要素をアレイの末尾に追加します。

buffer_info()

アレイの内容を記憶するために使っているバッファの、現在のメモリアドレスと要素数の入ったタプル(address,length) を返します。バイト単位で表したメモリバッファの大きさはarray.buffer_info()[1]*array.itemsize で計算できます。例えばioctl() 操作のような、メモリアドレスを必要とする低レベルな (そして、本質的に危険な) I/Oインターフェースを使って作業する場合に、ときどき便利です。アレイ自体が存在し、長さを変えるような演算を適用しない限り、有効な値を返します。

注釈

C やC++ で書いたコードからアレイオブジェクトを使う場合 (buffer_info() の情報を使う意味のある唯一の方法です) は、アレイオブジェクトでサポートしているバッファインターフェースを使う方がより理にかなっています。このメソッドは後方互換性のために保守されており、新しいコードでの使用は避けるべきです。バッファインターフェースの説明はバッファプロトコル (buffer Protocol) にあります。

byteswap()

アレイのすべての要素に対して「バイトスワップ」 (リトルエンディアンとビッグエンディアンの変換) を行います。このメソッドは大きさが 1、2、4 および 8 バイトの値のみをサポートしています。他の種類の値に使うとRuntimeError を送出します。異なるバイトオーダを使うマシンで書かれたファイルからデータを読み込むときに役に立ちます。

count(x)

シーケンス中のx の出現回数を返します。

extend(iterable)

iterable から要素を取り出し、アレイの末尾に要素を追加します。iterable が別のアレイ型である場合、二つのアレイは全く 同じ型コードでなければなりません。それ以外の場合にはTypeError を送出します。iterable がアレイでない場合、アレイに値を追加できるような正しい型の要素からなるイテレーション可能オブジェクトでなければなりません。

frombytes(buffer)

Appends items from thebytes-like object, interpretingits content as an array of machine values (as if it had been readfrom a file using thefromfile() method).

Added in version 3.2:明確化のためfromstring() の名前がfrombytes() に変更されました。

fromfile(f,n)

ファイルオブジェクトf から (マシンのデータ形式そのままで)n 個の要素を読み出し、アレイの末尾に要素を追加します。n 個未満の要素しか読めなかった場合はEOFError を送出しますが、それまでに読み出せた値はアレイに追加されます。

fromlist(list)

リストから要素を追加します。型に関するエラーが発生した場合にアレイが変更されないことを除き、forxinlist:a.append(x) と同じです。

fromunicode(s)

Extends this array with data from the given Unicode string.The array must have type code'u' or'w'; otherwise aValueError is raised.Usearray.frombytes(unicodestring.encode(enc)) to append Unicode data to anarray of some other type.

index(x[,start[,stop]])

Return the smallesti such thati is the index of the first occurrence ofx in the array. The optional argumentsstart andstop can bespecified to search forx within a subsection of the array. RaiseValueError ifx is not found.

バージョン 3.10 で変更:Added optionalstart andstop parameters.

insert(i,x)

アレイ中の位置i の前に値x をもつ新しい要素を挿入します。i の値が負の場合、アレイの末尾からの相対位置として扱います。

pop([i])

アレイからインデクスがi の要素を取り除いて返します。オプションの引数はデフォルトで-1 になっていて、最後の要素を取り除いて返すようになっています。

remove(x)

アレイ中のx のうち、最初に現れたものを取り除きます。

clear()

Remove all elements from the array.

Added in version 3.13.

reverse()

アレイの要素の順番を逆にします。

tobytes()

array をマシンの値の array に変換して、 bytes の形で返します (tofile() メソッドを使ってファイルに書かれるバイト列と同じです)。

Added in version 3.2:tostring() is renamed totobytes() for clarity.

tofile(f)

すべての要素を (マシンの値の形式で)file objectf に書き込みます。

tolist()

アレイを同じ要素を持つ普通のリストに変換します。

tounicode()

Convert the array to a Unicode string. The array must have a type'u' or'w';otherwise aValueError is raised. Usearray.tobytes().decode(enc) toobtain a Unicode string from an array of some other type.

The string representation of array objects has the formarray(typecode,initializer).Theinitializer is omitted if the array is empty, otherwise it isa Unicode string if thetypecode is'u' or'w', otherwise it isa list of numbers.The string representation is guaranteed to be able to be converted back to anarray with the same type and value usingeval(), so long as thearray class has been imported usingfromarrayimportarray.Variablesinf andnan must also be defined if it containscorresponding floating-point values.Examples:

array('l')array('w','hello\u2641')array('l',[1,2,3,4,5])array('d',[1.0,2.0,3.14,-inf,nan])

参考

struct モジュール

異なる種類のバイナリデータのパックおよびアンパック。

NumPy

NumPy パッケージは、別の配列型を定義しています。