您当前的位置:首页 > 计算机 > 编程开发 > Python

封装Python列表实现多下标访问

时间:09-04来源:作者:点击数:

封装Python列表实现多下标访问

class MyArray(object):

    def __init__(self, values):

        #values can be of any kinds which can be converted into list

        self.__data = list(values)

        
    #多下标访问列表元素 

    def __getitem__(self, index):

        length = len(self.__data)

        #index can be an integer

        if isinstance(index, int) and index<length:

            return self.__data[index]

        #index can also be a list/tuple which has many integers

        elif isinstance(index, (list,tuple)):

            #ensure that all integers given must < the length of data

            for i in index:

                if not (isinstance(i,int) and i<length):

                    return 'index error'

            result = []

            for item in index:

                result.append(self.__data[item])

            return result

        else:

            return 'index error'


   #多下标元素赋值

    def __setitem__(self, index, value):

        length = len(self.__data)

        if isinstance(index, int) and index<length:

            self.__data[index] = value

        elif isinstance(index, (list,tuple)):

            for i in index:

                if not (isinstance(i,int) and i<length):

                    raise Exception('index error')

            if isinstance(value, (list,tuple)):

                if len(index) == len(value):

                    for i, v in enumerate(index):

                        self.__data[v] = value[i]

                else:

                    raise Exception('values and index must be of the same length')

            elif isinstance(value, (int,float,complex,str)):

                for i in index:

                    self.__data[i] = value

            else:

                raise Exception('value error')

        else:

            raise Exception('index error')

    def __repr__(self):

        return str(self.__data)

用法演示:

>>> from myArr import MyArray

>>> x = MyArray(range(20))

>>> x

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> x[3]

3

>>> x[3] = 'a'

>>> x

[0, 1, 2, 'a', 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> x[[3,3,5]]

['a', 'a', 5]

>>> x[[3,3,5]] = ['test', 'hello', 100]

>>> x

[0, 1, 2, 'hello', 4, 100, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> x[[1,3,5]] = ['test', 'hello', 100]

>>> x

[0, 'test', 2, 'hello', 4, 100, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> x[100]

'index error'

>>> x[100] = 3

Traceback (most recent call last):

  File "<pyshell#90>", line 1, in <module>

    x[100] = 3

  File "C:/Python35\myArr.py", line 44, in __setitem__

    raise Exception('index error')

Exception: index error

>>> x[[1,100]] = 3

Traceback (most recent call last):

  File "<pyshell#91>", line 1, in <module>

    x[[1,100]] = 3

  File "C:/Python35\myArr.py", line 31, in __setitem__

    raise Exception('index error')

Exception: index error

>>> x[list(range(20,2))] = 0

>>> x

[0, 'test', 2, 'hello', 4, 100, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> y=list(range(20,2))

>>> x[y] = 0

>>> x

[0, 'test', 2, 'hello', 4, 100, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> x[[1,3,5,7,9]] = 0

>>> x

[0, 0, 2, 0, 4, 0, 6, 0, 8, 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门