目录
1 一维数组
数组(array)表示的是可以在给定的索引位置访问或替代的项的一个序列。
1.1 数组数据结构
- 数组是一个数据结构
- 支持按照位置对某一项的随机访问,且这种访问的时间是常数
- 在创建数组时,给定了用于存储数据的位置的一个数目,并且数组的长度保持固定
- 插入和删除需要移动数据元素
- 创建一个新的,较大的或较小的数组,可能也需要移动数据元素
- 支持的操作
- 在给定位置访问或替代数组的一个项
- 查看数组的长度
- 获取数组的字符串表示
- 数组操作及Array类的方法
用户的数组操作 | Array类中的方法 |
a = Array(10) | __init__(capacity, fillVaule = None) |
len(a) | __len__() |
str(a) | __str__() |
for item in a: | __iter__() |
a[index] | __getitem__(index) |
a[index] = newItem | __setitem__(index, newItem) |
- Python代码:定义Array类
# -*- encoding: utf-8 -*-
# Author: ZFT
"""
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 by default.
"""
class Array(object):
"""Represents an array."""
def __init__(self, capacity, fillValue = None):
"""Capacity is the static size of the array.
fillValue is placed at each position."""
self._items = list()