python通过什么实现映射


当前第2页 返回上一页

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

from collections import MutableMapping

 

class MyMap(MutableMapping):

 

    class item():

 

        def __init__(self,key,value):

            self.key = key

            self.value = value

 

        def __eq__(self, other):

            return self.key == other.key

 

        def __ne__(self, other):

            return self.key != other.key

 

    def __init__(self):

        self.table = []

 

    def __getitem__(self, item):

        for i in self.table:

            if i.key == item:

                return i.value

        raise KeyError('Key Error: '+ repr(item))

 

    def __setitem__(self, key, value):

        for i in self.table:

            if i.key == key:

                i.value = value

                return

        self.table.append(self.item(key,value))

 

    def __delitem__(self, key):

        for n,i in enumerate(self.table):

            if i.key == key:

                self.pop(n)

                return

        raise KeyError('Key Error: '+ repr(key))

 

    def __len__(self):

        return len(self.table)

 

    def __iter__(self):

        for i in self.table:

            yield i.key

上面这个办法很简单,但是却不是很有效率,我们每次都需要遍历一遍列表才能找到该键的索引,所以时间复杂的为O(n)。

更多Python相关技术文章,请访问Python教程栏目进行学习!

以上就是python通过什么实现映射的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python如何实现格式化输出

anaconda是什么?

什么是Python cgi编程?编程前需要做哪些准备?

Python怎么找外包

Python 类对象和实例对象动态添加方法

Python 通配符删除文件

Python如何去掉空格

Python pow函数怎么用

Python运算符-位运算符的实际运用与深入分析

Python 实现在文件中的每一行添加一个逗号

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...