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 Тип

Тип Python

Мінімальний розмір у байтах

Примітки

'b''

підписаний символ

внутр

1

'B'

беззнаковий символ

внутр

1

'u''

Py_UNICODE

символ Unicode

2

(1)

'h''

підписаний короткий

внутр

2

'H''

непідписаний короткий

внутр

2

'я''

підписаний внутр

внутр

2

'Я''

unsigned int

внутр

2

'l'

підписаний довго

внутр

4

'L'

беззнаковий довгий

внутр

4

'q''

підписаний довгий довгий

внутр

8

'Q''

без знака довгий довгий

внутр

8

'f''

плавати

плавати

4

'd''

подвійний

плавати

8

Примітки:

  1. The 'u' type code corresponds to Python’s obsolete unicode character (Py_UNICODE which is wchar_t). Depending on the platform, it can be 16 bits or 32 bits.

    'u' will be removed together with the rest of the Py_UNICODE API.

    Deprecated since version 3.3, will be removed in version 4.0.

The actual representation of values is determined by the machine architecture (strictly speaking, by the C implementation). The actual size can be accessed through the itemsize attribute.

Модуль визначає наступний тип:

class array.array(typecode[, initializer])

A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, a bytes-like object, or iterable over elements of the appropriate type.

If given a list or string, the initializer is passed to the new array’s fromlist(), frombytes(), or fromunicode() method (see below) to add initial items to the array. Otherwise, the iterable initializer is passed to the extend() method.

Викликає подію аудиту array.__new__ з аргументами typecode, initializer.

array.typecodes

Рядок із усіма доступними кодами типів.

Об’єкти-масиви підтримують звичайні операції послідовності індексування, нарізки, конкатенації та множення. Якщо використовується призначення фрагментів, призначене значення має бути об’єктом масиву з таким же кодом типу; у всіх інших випадках виникає TypeError. Об’єкти-масиви також реалізують інтерфейс буфера, і їх можна використовувати скрізь, де підтримуються байтоподібні об’єкти.

The following data items and methods are also supported:

array.typecode

Символ коду типу, який використовується для створення масиву.

array.itemsize

Довжина в байтах одного елемента масиву у внутрішньому представленні.

array.append(x)

Додайте новий елемент зі значенням x у кінець масиву.

array.buffer_info()

Return a tuple (address, length) giving the current memory address and the length in elements of the buffer used to hold array’s contents. The size of the memory buffer in bytes can be computed as array.buffer_info()[1] * array.itemsize. This is occasionally useful when working with low-level (and inherently unsafe) I/O interfaces that require memory addresses, such as certain ioctl() operations. The returned numbers are valid as long as the array exists and no length-changing operations are applied to it.

Примітка

При використанні об’єктів масиву з коду, написаного на C або C++ (єдиний спосіб ефективного використання цієї інформації), має сенс використовувати інтерфейс буфера, який підтримується об’єктами масиву. Цей метод підтримується для зворотної сумісності, і його слід уникати в новому коді. Інтерфейс буфера задокументовано в Буферний протокол.

array.byteswap()

«Побайтувати» всі елементи масиву. Це підтримується лише для значень розміром 1, 2, 4 або 8 байтів; для інших типів значень виникає RuntimeError. Це корисно під час читання даних із файлу, записаного на машині з іншим порядком байтів.

array.count(x)

Повертає кількість входжень x в масиві.

array.extend(iterable)

Додайте елементи з iterable у кінець масиву. Якщо iterable є іншим масивом, він повинен мати точно той самий код типу; якщо ні, буде викликано TypeError. Якщо iterable не є масивом, він має бути повторюваним, а його елементи мають мати правильний тип для додавання до масиву.

array.frombytes(s)

Appends items from the string, interpreting the string as an array of machine values (as if it had been read from a file using the fromfile() method).

Нове в версії 3.2: fromstring() is renamed to frombytes() for clarity.

array.fromfile(f, n)

Прочитайте n елементів (як машинні значення) з file object f і додайте їх у кінець масиву. Якщо доступно менше n елементів, виникає EOFError, але доступні елементи все одно вставляються в масив.

array.fromlist(list)

Додавання елементів зі списку. Це еквівалентно для x у списку: a.append(x) за винятком того, що якщо є помилка типу, масив не змінюється.

array.fromstring()

Deprecated alias for frombytes().

Deprecated since version 3.2, will be removed in version 3.9.

array.fromunicode(s)

Extends this array with data from the given unicode string. The array must be a type 'u' array; otherwise a ValueError is raised. Use array.frombytes(unicodestring.encode(enc)) to append Unicode data to an array of some other type.

array.index(x)

Return the smallest i such that i is the index of the first occurrence of x in the array.

array.insert(i, x)

Вставте новий елемент зі значенням x в масив перед позицією i. Від’ємні значення розглядаються як відносні до кінця масиву.

array.pop([i])

Вилучає з масиву елемент з індексом i і повертає його. Необов’язковий аргумент за умовчанням має значення -1, тому за замовчуванням останній елемент видаляється та повертається.

array.remove(x)

Видаліть перше входження x з масиву.

array.reverse()

Змінити порядок елементів у масиві.

array.tobytes()

Перетворіть масив на масив машинних значень і поверніть представлення байтів (та сама послідовність байтів, яка була б записана у файл за допомогою методу tofile()).

Нове в версії 3.2: tostring() is renamed to tobytes() for clarity.

array.tofile(f)

Запишіть усі елементи (як машинні значення) в file object f.

array.tolist()

Перетворіть масив на звичайний список з тими самими елементами.

array.tostring()

Deprecated alias for tobytes().

Deprecated since version 3.2, will be removed in version 3.9.

array.tounicode()

Convert the array to a unicode string. The array must be a type 'u' array; otherwise a ValueError is raised. Use array.tobytes().decode(enc) to obtain a unicode string from an array of some other type.

When an array object is printed or converted to a string, it is represented as array(typecode, initializer). The initializer is omitted if the array is empty, otherwise it is a string if the typecode is 'u', otherwise it is a list of numbers. The string 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. Examples:

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

Дивись також

Модуль struct

Упаковка та розпакування різнорідних двійкових даних.

Module xdrlib

Packing and unpacking of External Data Representation (XDR) data as used in some remote procedure call systems.

The Numerical Python Documentation

The Numeric Python extension (NumPy) defines another array type; see http://www.numpy.org/ for further information about Numerical Python.