社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
Python没有提供直接的数组类型数据结构,但是可以通过从类库array中导入
数组(array)表示的是可以在给定的索引位置访问或替代的项的一个序列
根据定义,Python的列表类似于数组(实际上,列表的底层结构就是数组)
和Python列表不同的是,数组一旦确定,它的长度(容量)也就确定了
在Python的内置模块array
中提供了一般语言的数组功能
array.Array
是一个类,在Python中需要手动导入
from array import Array
具有讽刺意味的是,Array类使用Python列表来保存其所有项
Python数组类提供了如下方法接口
用户的数组操作 Array类中的方法
-------------- -----------------
a = Array(10) # __init__(capacity, fillValue=None)
len(a) # __len__()
str(a) # __str__()
for item in a: #__iter__()
a[index] # __getitem__(index)
a[index] = newItme # __setitem__(index, newItem)
Python数组类的__init__(capacity, fillValue=None)
注意到默认填充元素为None,如果需要可以重写该方法
不管怎么说,Python数组都像是受到限制的列表——但正是这种限制提供了一定意义上的安全性,有利有弊
array.Array
类的定义模块
"""
File: arrays.py
An array is like a list , but the client can use
only [], len, iter, and str
To instantiate, use
<variable> = Array(<capacity>, <optional fill value>)
The fill value is None default
"""
class Array(object):
"""Represents an array."""
def __init__(self, capacity, fillValue=None):
"""Capcaity is the static size of the array.
fillValue is plased at each position."""
self._items = list()
for count in range(capacity):
self._items.append(fillValue)
def __len__(self):
"""->The capacity of the array."""
return len(self._items)
def __str__(self):
"""->The string representation of the array."""
return str(self._items)
def __iter__(self):
"""Support traversal with a for loop."""
return iter(self._items)
def __getitem__(self, index):
"""Subscript operator for access at index."""
return self._items[index]
def __setitem__(self, index, newItem):
self._item[index] = newItem
在命令行下,键入
pip3 install numpy --user python3
numpy是一个优秀的Python第三方库,支持大量的数学计算,我们使用它来『玩一玩』多维数组(矩阵)
numpy的数组称为ndarray——使用numpy,开发人员可以执行以下操作:1)数组的算术运算和逻辑运算,2)傅立叶变换和用于图形操作的例程,3)与线性代数以有关的操作
numpy.ndarray
和标准库的array.array
的区别在于,后者只处理一维数组,而前者还提供多位数组的支持
使用下面的函数创建一个ndarray
对象
# object: 任何暴露数组接口的对象都会返回一个数组或任何(嵌套)序列
# dtype: 数组的所需数据类型
# copy: 可选,默认为True,对象是否被复制
# order: C(按行)、F(按列)、A(任意,默认)
# subok: 默认情况下,返回的数组被强制为基类数组,如果为True,则返回子类
# ndmin: 指定返回数组的最小维数
numpy.array(objecy, dtype=None, copy=True, order=None, subok=False, ndmin=0)
numpy
作为一款优秀的Python第三方库,这里只是简单介绍——以后会有详细的文章专门进行讲解
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!