1.前言:
数据结构(data structure)和具体数据类型(concrete data type)这两个术语,指的是集合数据的内部表示。在编程语言中,最常用来实现集合的两种数据结构是数组和链表结构。
这两种类型的结构采用不同的方法在计算机内存中存储和访问数据。这些方法反过来导致了操作该集合的算法中的不同的时间/空间取舍。
2.定义:
在给定的索引位置访问或替代的项的一个序列,即:可在给定的位置访问或替代数组的一个项,查看数组的长度,以及获取其字符串表示,不能添加、删除某个位置的项或者改变数组的长度大小。
3.数组操作以及对应代码中的操作方法:
用户的数组操作 | 操作方法 |
a = Array(10) | __init__(capacity,fillValue=None) |
len(a) | __len__() |
str(a) | __str__() |
for item in a: | __iter__() |
a[index] | __getitem__(index) |
a[index]=newItem | __setitem__(index,newItem) |
4.代码实现:
"""An Array is like a list,but the client can use only [],len,iter,and str."""
class Array(object):
""" Representts an array."""
def __init__(self,capacity,fileValue=None):
"""Capacity is the static size of the array.
fillValue is placed at each position."""
self._items =list()
for count in range(capacity):
self._items.append(fileValue)
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):
"""Supports traversal with a for loop"""
return iter(self._items)
def __getitem__(self,index):
"""Subscript operator for access at index."""
return iter(self._items[index])
def __setitem__(self,index,newItem):
"""Subscript operator for replacement at index."""
self._items[index] = newItem