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:

Type code C Type Python Type Minimum size in bytes
'c' char character 1
'b' signed char int 1
'B' unsigned char int 1
'u' Py_UNICODE Unicode character 2 (see note)
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int long 2
'l' signed long int 4
'L' unsigned long long 4
'f' float float 4
'd' double float 8

Note

The 'u' typecode corresponds to Python’s unicode character. On narrowUnicode builds this is 2-bytes, on wide builds this is 4-bytes.

The actual representation of values is determined by the machine architecture(strictly speaking, by the C implementation). The actual size can be accessedthrough the itemsize attribute. The values stored for 'L' and'I' items will be represented as Python long integers when retrieved,because Python’s plain integer type cannot represent the full range of C’sunsigned (long) integers.

The module defines the following type:

class array.array(typecode[, initializer])

A new array whose items are restricted by typecode, and initializedfrom the optional initializer value, which must be a list, string, or iterableover elements of the appropriate type.

Changed in version 2.4: Formerly, only lists or strings were accepted.

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

array.ArrayType

Obsolete alias for array.

Array objects support the ordinary sequence operations of indexing, slicing,concatenation, and multiplication. When using slice assignment, the assignedvalue must be an array object with the same type code; in all other cases,TypeError is raised. Array objects also implement the buffer interface,and may be used wherever buffer objects are supported.

The following data items and methods are also supported:

array.typecode

The typecode character used to create the array.

array.itemsize

The length in bytes of one array item in the internal representation.

array.append(x)

Append a new item with value x to the end of the array.

Note:在Python3.6下有些变化,有些typecode约束不支持一些初始化器,如下图所示:

Python学习笔记之array

相关文章:

  • 2021-07-28
  • 2021-06-22
  • 2021-10-04
  • 2022-12-23
  • 2021-12-24
  • 2021-11-28
  • 2022-01-22
  • 2021-05-05
猜你喜欢
  • 2021-08-20
  • 2022-12-23
  • 2021-12-21
  • 2022-02-13
  • 2022-12-23
  • 2021-09-24
  • 2021-12-28
相关资源
相似解决方案