array
— Efficient arrays of numeric values¶
This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character. The following type codes are defined:
형 코드 |
C 형 |
파이썬 형 |
최소 크기(바이트) |
노트 |
---|---|---|---|---|
|
signed char |
int |
1 |
|
|
unsigned char |
int |
1 |
|
|
wchar_t |
유니코드 문자 |
2 |
(1) |
|
signed short |
int |
2 |
|
|
unsigned short |
int |
2 |
|
|
signed int |
int |
2 |
|
|
unsigned int |
int |
2 |
|
|
signed long |
int |
4 |
|
|
unsigned long |
int |
4 |
|
|
signed long long |
int |
8 |
|
|
unsigned long long |
int |
8 |
|
|
float |
float |
4 |
|
|
double |
float |
8 |
노트:
플랫폼에 따라 16비트 또는 32비트 일 수 있습니다.
버전 3.9에서 변경:
array('u')
는 이제 폐지된Py_UNICODE
대신wchar_t
를 C형으로 사용합니다.Py_UNICODE
는 파이썬 3.3부터wchar_t
의 별칭이라서 이 변경은 동작에 영향을 미치지 않습니다.버전 3.3에서 폐지되었습니다, 버전 4.0에서 제거됩니다..
값의 실제 표현은 기계 아키텍처에 의해(엄격히 말하자면 C 구현에 의해) 결정됩니다. 실제 크기는 array.itemsize
어트리뷰트를 통해 액세스할 수 있습니다.
모듈은 다음 항목을 정의합니다:
- array.typecodes¶
사용 가능한 모든 형 코드가 있는 문자열.
모듈은 다음 형을 정의합니다:
- class array.array(typecode[, initializer])¶
항목이 typecode에 의해 제한되는 새 배열, 선택적인 initializer 값으로 초기화되는데,
bytes
나bytearray
객체, 유니코드 문자열 또는 적절한 형의 요소에 대한 이터러블이어야 합니다.bytes
나bytearray
객체가 주어지면, initializer는 새 배열의frombytes()
메서드로 전달됩니다; 유니코드 문자열이 주어지면, initializer는fromunicode()
메서드로 전달됩니다; 그렇지 않으면, initializer의 이터레이터가extend()
메서드에 전달되어 배열에 초기 항목들을 추가합니다.배열 객체는 인덱싱, 슬라이싱, 이어붙이기 및 곱셈과 같은 일반적인 시퀀스 연산을 지원합니다. 슬라이스 대입을 사용할 때, 대입되는 값은 같은 형 코드의 배열 객체여야 합니다; 다른 모든 경우에는,
TypeError
가 발생합니다. 배열 객체는 버퍼 인터페이스도 구현하며, 바이트열류 객체가 지원되는 곳이면 어디에서나 사용될 수 있습니다.typecode
,initializer
인자로 감사 이벤트(auditing event)array.__new__
를 발생시킵니다.- typecode¶
배열을 만드는 데 사용된 typecode 문자.
- itemsize¶
내부 표현에서 하나의 배열 항목의 길이 (바이트).
- append(x)¶
배열의 끝에 값 x로 새 항목을 추가합니다.
- buffer_info()¶
배열의 내용을 담는 데 사용된 버퍼의 현재 메모리 주소와 요소의 수로 표현한 길이를 제공하는 튜플
(address, length)
를 반환합니다. 바이트 단위의 메모리 버퍼 크기는array.buffer_info()[1] * array.itemsize
로 계산할 수 있습니다. 이것은 특정ioctl()
연산과 같은 메모리 주소가 필요한 저수준(그리고 근본적으로 안전하지 않은) I/O 인터페이스로 작업할 때 간혹 유용합니다. 반환된 숫자는 배열이 존재하고 길이 변경 연산이 적용되지 않는 한 유효합니다.참고
C나 C++로 작성된 코드(이 정보를 효율적으로 사용하는 유일한 방법)에서 배열 객체를 사용할 때, 배열 객체가 지원하는 버퍼 인터페이스를 사용하는 것이 좋습니다. 이 메서드는 이전 버전과의 호환성을 위해 유지되며 새 코드에서는 사용하지 않아야 합니다. 버퍼 인터페이스는 버퍼 프로토콜에 설명되어 있습니다.
- byteswap()¶
배열의 모든 항목을 “바이트 스와프(byteswap)” 합니다. 1, 2, 4 또는 8바이트 크기의 값에 대해서만 지원됩니다; 다른 형의 값이면
RuntimeError
가 발생합니다. 바이트 순서가 다른 컴퓨터에서 작성된 파일에서 데이터를 읽을 때 유용합니다.
- count(x)¶
배열 내에서 x가 등장하는 횟수를 반환합니다.
- extend(iterable)¶
iterable의 항목을 배열의 끝에 추가합니다. iterable이 다른 배열이면, 정확히 같은 형 코드를 가져야 합니다; 그렇지 않으면,
TypeError
가 발생합니다. iterable이 배열이 아니면, 이터러블이어야 하며 요소는 배열에 추가할 올바른 형이어야 합니다.
- frombytes(buffer)¶
바이트열류 객체에서 항목을 추가합니다. 내용을 기곗값(machine value)의 배열로 해석합니다 (마치
fromfile()
메서드를 사용하여 파일에서 읽은 것처럼).버전 3.2에 추가:
fromstring()
은 명확하게 하려고frombytes()
로 이름을 바꿨습니다.
- fromfile(f, n)¶
파일 객체 f에서 (기곗값으로) n 항목을 읽고 배열의 끝에 추가합니다. n 미만의 항목만 사용할 수 있으면
EOFError
가 발생하지만, 사용 가능한 항목은 여전히 배열에 삽입됩니다.
- fromlist(list)¶
리스트에서 항목을 추가합니다. 이것은 형 에러가 있으면 배열이 변경되지 않는다는 점만 제외하면
for x in list: a.append(x)
와 동등합니다.
- fromunicode(s)¶
Extends this array with data from the given Unicode string. The array must have type code
'u'
; otherwise aValueError
is raised. Usearray.frombytes(unicodestring.encode(enc))
to append Unicode data to an array of some other type.
- index(x[, start[, stop]])¶
Return the smallest i such that i is the index of the first occurrence of x in the array. The optional arguments start and stop can be specified to search for x within a subsection of the array. Raise
ValueError
if x is not found.버전 3.10에서 변경: Added optional start and stop parameters.
- insert(i, x)¶
i 위치 앞에 값이 x인 새 항목을 배열에 삽입합니다. 음수 값은 배열 끝에 상대적인 값으로 처리됩니다.
- pop([i])¶
배열에서 인덱스 i에 있는 항목을 제거하고 이를 반환합니다. 선택적 인자의 기본값은
-1
이므로, 기본적으로 마지막 항목이 제거되고 반환됩니다.
- remove(x)¶
배열에서 첫 번째 x를 제거합니다.
- reverse()¶
배열의 항목 순서를 뒤집습니다.
- tobytes()¶
배열을 기곗값 배열로 변환하고 바이트열 표현(
tofile()
메서드로 파일에 기록될 바이트 시퀀스와 같습니다)을 반환합니다.버전 3.2에 추가:
tostring()
은 명확하게 하려고tobytes()
로 이름을 바꿨습니다.
- tolist()¶
배열을 같은 항목이 있는 일반 리스트로 변환합니다.
- tounicode()¶
Convert the array to a Unicode string. The array must have a type
'u'
; otherwise aValueError
is raised. Usearray.tobytes().decode(enc)
to obtain a Unicode string from an array of some other type.
The string representation of array objects has the form
array(typecode, initializer)
.
The initializer is omitted if the array is empty, otherwise it is
a Unicode string if the typecode is 'u'
, otherwise it is
a list of numbers.
The string representation is guaranteed to be able to be converted back to an
array with the same type and value using eval()
, so long as the
array
class has been imported using from array import array
.
Variables inf
and nan
must also be defined if it contains
corresponding floating point values.
Examples:
array('l')
array('u', 'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14, -inf, nan])