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怎么去掉数据的方括号

Python实现王者荣耀刷金币脚本功能

Python类怎么理解

Python装饰器之property()教程详解

Python循环语句怎么写

Python中列表、字符串、字典常用操作总结

什么是Python和php?Python与php有什么区别

Python怎么运行脚本?

Python解方程的技巧介绍(代码示例)

怎么在Python安装pil

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




打赏

取消

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

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

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

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

评论

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