python学习笔记(六)之内置容器dict的妙用
2014-10-17 15:28
411 查看
直接跳过了tuple和其它内置容器,因为大同小异,可以在官方文档查得,只要用心阅读再稍加推敲即可使用,但是这里特别说一下dict,一个我觉得比较特殊的内置容器。
官方文档如此解释dict——A mapping object
maps hashable values
to arbitrary objects.也就是说dict全称dictionary,在其他语言中也称为map。
map的特点是什么?那就是使用键-值(key-value)存储,具有极快的查找速度。
没错,重点就是具有极快的查找速度。为什么dict查找速度这么快?这里可以类比查字典,如果我们使用list存储字典元素,在list中查找元素就等于一页一页的将字典往后翻,元素越多,“翻页”越多,查询越困难也越慢。
但是dict不同,dict等同于建立了索引表(例如字典中的拼音查询),只要查这个字典元素的对应页码,然后直接翻到该页,找到这个字,无论找哪个字,这种查找速度都非常快,不会随着字典大小的增加而变慢。
用算法复杂度来表示,list的时间复杂度就是O(n),而dict的时间复杂度为O(1)——自然快很多。
附上leetcode一题,很能说明问题。问题如下:
换用dict类,果然通过:
官方文档如此解释dict——A mapping object
maps hashable values
to arbitrary objects.也就是说dict全称dictionary,在其他语言中也称为map。
map的特点是什么?那就是使用键-值(key-value)存储,具有极快的查找速度。
没错,重点就是具有极快的查找速度。为什么dict查找速度这么快?这里可以类比查字典,如果我们使用list存储字典元素,在list中查找元素就等于一页一页的将字典往后翻,元素越多,“翻页”越多,查询越困难也越慢。
但是dict不同,dict等同于建立了索引表(例如字典中的拼音查询),只要查这个字典元素的对应页码,然后直接翻到该页,找到这个字,无论找哪个字,这种查找速度都非常快,不会随着字典大小的增加而变慢。
用算法复杂度来表示,list的时间复杂度就是O(n),而dict的时间复杂度为O(1)——自然快很多。
附上leetcode一题,很能说明问题。问题如下:
Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2一开始我解决的方法十分暴力,直接遍历两次num这个list中的元素,分别相加,然后考查是否等于target,代码如下:
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): n = len(num) index = [] i=0;j=n-1 while target != num[i] + num[j] : if i<j: j=j-1 else: j=n-1 i=i+1 index = [i+1,j+1] return tuple(index)提交代码显示TLE,不言而喻,这是一个O(n2)的查找代码,显然是不能通过的。
换用dict类,果然通过:
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): dict = {}#dict = {"num[i]":i} for i in range(len(num)): if target - num[i] in dict: index1 = i + 1 index2 = dict[target - num[i]] + 1 print (min(index1,index2),max(index1,index2))#actually should use return not print,but it's just for test. else: dict[num[i]] = i
相关文章推荐
- Python学习笔记(三十三)常用内置模块(2)collections_namedtuple_deque_defaultdict_OrderedDict_Counter
- python学习笔记(五)之内置容器List
- python 学习笔记——字典(dict)
- Python学习笔记之dict、set
- Python学习笔记(四)dict和set
- Python常用的内置序列结构(列表、元组、字典)学习笔记
- Python学习笔记:字典(dict)有关内容
- python学习笔记之内置数据类型
- Python 类中的__dict__学习笔记
- Python 学习笔记 高性能容器 collections
- 【零基础入门学习Python笔记014】字符串:各种奇葩的内置方法
- Python 2.7 学习笔记 内置语句、函数、标准库
- Python常用的内置序列结构(列表、元组、字典)学习笔记
- python2.7学习笔记(4) ——条件判断、循环、dict、set
- Python学习笔记之映射类型字典(dict)
- Python3.3 学习笔记4 - 函数 - 内置和其他一些函数
- 【Python学习笔记】list/dict对象复制的误区与正确方法
- Python学习笔记,内置数据类型。
- python学习笔记—使用dict和set
- Python的dict字典结构操作方法学习笔记