Python算法系列(三):数组 - Go语言中文社区

Python算法系列(三):数组


Python没有提供直接的数组类型数据结构,但是可以通过从类库array中导入


概述:数组v.s.列表

数组(array)表示的是可以在给定的索引位置访问或替代的项的一个序列

根据定义,Python的列表类似于数组(实际上,列表的底层结构就是数组)

和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 

多维数组:学习使用numpy(新手级别)

numpy安装方法

在命令行下,键入

pip3 install numpy --user python3

numpy基本介绍

numpy是一个优秀的Python第三方库,支持大量的数学计算,我们使用它来『玩一玩』多维数组(矩阵)

numpy模拟矩阵

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第三方库,这里只是简单介绍——以后会有详细的文章专门进行讲解

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/abc_12366/article/details/79861134
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-04-08 10:08:58
  • 阅读 ( 1297 )
  • 分类:算法

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢