第五章:Python高级编程-深入Python的dict和set

课程:Python3高级核心技术

5.1 dict的abc继承关系

class Mapping(Collection):

    __slots__ = ()

    """A Mapping is a generic container for associating key/value
pairs. This class provides concrete generic implementations of all
methods except for __getitem__, __iter__, and __len__. """ @abstractmethod
def __getitem__(self, key):
raise KeyError def get(self, key, default=None):
'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
try:
return self[key]
except KeyError:
return default def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True def keys(self):
"D.keys() -> a set-like object providing a view on D's keys"
return KeysView(self) def items(self):
"D.items() -> a set-like object providing a view on D's items"
return ItemsView(self) def values(self):
"D.values() -> an object providing a view on D's values"
return ValuesView(self) def __eq__(self, other):
if not isinstance(other, Mapping):
return NotImplemented
return dict(self.items()) == dict(other.items()) __reversed__ = None class MutableMapping(Mapping): __slots__ = () """A MutableMapping is a generic container for associating
key/value pairs. This class provides concrete generic implementations of all
methods except for __getitem__, __setitem__, __delitem__,
__iter__, and __len__. """ @abstractmethod
def __setitem__(self, key, value):
raise KeyError @abstractmethod
def __delitem__(self, key):
raise KeyError __marker = object() def pop(self, key, default=__marker):
'''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
'''
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value def popitem(self):
'''D.popitem() -> (k, v), remove and return some (key, value) pair
as a 2-tuple; but raise KeyError if D is empty.
'''
try:
key = next(iter(self))
except StopIteration:
raise KeyError from None
value = self[key]
del self[key]
return key, value def clear(self):
'D.clear() -> None. Remove all items from D.'
try:
while True:
self.popitem()
except KeyError:
pass def update(*args, **kwds):
''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v
'''
if not args:
raise TypeError("descriptor 'update' of 'MutableMapping' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('update expected at most 1 arguments, got %d' %
len(args))
if args:
other = args[0]
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value def setdefault(self, key, default=None):
'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
try:
return self[key]
except KeyError:
self[key] = default
return default

5.2 dict的常用方法

class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""
def clear(self): # real signature unknown; restored from __doc__
""" D.clear() -> None. Remove all items from D. """
pass def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D """
pass @staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
""" Create a new dictionary with keys from iterable and values set to value. """
pass def get(self, *args, **kwargs): # real signature unknown
""" Return the value for key if key is in the dictionary, else default. """
pass def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items """
pass def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys """
pass def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
pass def popitem(self): # real signature unknown; restored from __doc__
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
"""
pass def setdefault(self, *args, **kwargs): # real signature unknown
"""
Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default.
"""
pass def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
pass def values(self): # real signature unknown; restored from __doc__
""" D.values() -> an object providing a view on D's values """
pass def __contains__(self, *args, **kwargs): # real signature unknown
""" True if the dictionary has the specified key, else False. """
pass def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
# (copied from class doc)
"""
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass __hash__ = None

5.3 dict的子类

"""
不建议直接继承dict,而是collections.UserDict
"""

5.4 set和frozenset

"""
set 集合 frozenset(不可变集合) 无序 不重复
""" s = set("abcde") # 迭代类型
print(s) # 向set添加数据
s.add()
s.update() difference() # 差值
- # 差集 # / & - #set 集合 fronzenset (不可变集合) 无序, 不重复
# s = set('abcdee')
# s = set(['a','b','c','d','e'])
s = {'a','b', 'c'}
# s = frozenset("abcde") #frozenset 可以作为dict的key
# print(s) #向set添加数据
another_set = set("cef")
re_set = s.difference(another_set)
re_set = s - another_set
re_set = s & another_set
re_set = s | another_set #set性能很高
# | & - #集合运算
print(re_set) print (s.issubset(re_set))
# if "c" in re_set:
# print ("i am in set")

5.5 dict和set的实现原理

"""
测试list和dict的性能
""" from random import randint def load_list_data(total_nums, target_nums):
"""
从文件中读取数据,以list的方式返回
:param total_nums: 读取的数量
:param target_nums: 需要查询的数据的数量
"""
all_data = []
target_data = []
file_name = "G:/慕课网课程/AdvancePython/fbobject_idnew.txt"
with open(file_name, encoding="utf8", mode="r") as f_open:
for count, line in enumerate(f_open):
if count < total_nums:
all_data.append(line)
else:
break for x in range(target_nums):
random_index = randint(0, total_nums)
if all_data[random_index] not in target_data:
target_data.append(all_data[random_index])
if len(target_data) == target_nums:
break return all_data, target_data def load_dict_data(total_nums, target_nums):
"""
从文件中读取数据,以dict的方式返回
:param total_nums: 读取的数量
:param target_nums: 需要查询的数据的数量
"""
all_data = {}
target_data = []
file_name = "G:/慕课网课程/AdvancePython/fbobject_idnew.txt"
with open(file_name, encoding="utf8", mode="r") as f_open:
for count, line in enumerate(f_open):
if count < total_nums:
all_data[line] = 0
else:
break
all_data_list = list(all_data)
for x in range(target_nums):
random_index = randint(0, total_nums-1)
if all_data_list[random_index] not in target_data:
target_data.append(all_data_list[random_index])
if len(target_data) == target_nums:
break return all_data, target_data def find_test(all_data, target_data):
#测试运行时间
test_times = 100
total_times = 0
import time
for i in range(test_times):
find = 0
start_time = time.time()
for data in target_data:
if data in all_data:
find += 1
last_time = time.time() - start_time
total_times += last_time
return total_times/test_times if __name__ == "__main__":
# all_data, target_data = load_list_data(10000, 1000)
# all_data, target_data = load_list_data(100000, 1000)
# all_data, target_data = load_list_data(1000000, 1000) # all_data, target_data = load_dict_data(10000, 1000)
# all_data, target_data = load_dict_data(100000, 1000)
# all_data, target_data = load_dict_data(1000000, 1000)
all_data, target_data = load_dict_data(2000000, 1000)
last_time = find_test(all_data, target_data) #dict查找的性能远远大于list
#在list中随着list数据的增大 查找时间会增大
#在dict中查找元素不会随着dict的增大而增大
print(last_time) #1. dict的key或者set的值 都必须是可以hash的
#不可变对象 都是可hash的, str, fronzenset, tuple,自己实现的类 __hash__
#2. dict的内存花销大,但是查询速度快, 自定义的对象 或者python内部的对象都是用dict包装的
# 3. dict的存储顺序和元素添加顺序有关
# 4. 添加数据有可能改变已有数据的顺序


第五章:深入Python的dict和set的更多相关文章

  1. 第十五章、Python多线程之信号量和GIL

    目录 第十五章.Python多线程之信号量和GIL 1. 信号量(Semaphore) 2. GIL 说明: 第十五章.Python多线程之信号量和GIL 1. 信号量(Semaphore) 信号量用 ...

  2. 第十五章、Python多线程同步锁,死锁和递归锁

    目录 第十五章.Python多线程同步锁,死锁和递归锁 1. 引子: 2.同步锁 3.死锁 引子: 4.递归锁RLock 原理: 不多说,放代码 总结: 5. 大总结 第十五章.Python多线程同步 ...

  3. 第十五章、python中的进程操作-开启多进程

    目录 第十五章.python中的进程操作-开启多进程 一.multprocess模块 二.multprocess.process模块 三.Process()对象方法介绍 四.Process()对象属性 ...

  4. 第五章:Python基础の生成器、迭代器、序列化和虚拟环境的应用

    本课主题 生成器介紹和操作实战 迭代器介紹和操作实战 序例化和反序例化 Json 和 Pickle 操作实战 字符串格式化的应用 创建虚拟环境实战 本周作业 生成器介紹和操作实战 什么是生成器,生成器 ...

  5. 第十五章:Python の Web开发基础 (二) JavaScript与DOM

    本課主題 JavaScript 介绍 DOM 介绍 JavaScript 介绍 JavaScript 是一门编程语言,它可以让网页动起来的,JavaScript 的变量有两种,一个是局部变量:一个是全 ...

  6. 《python for data analysis》第五章,pandas的基本使用

    <利用python进行数据分析>一书的第五章源码与读书笔记 直接上代码 # -*- coding:utf-8 -*-# <python for data analysis>第五 ...

  7. python学习心得第五章

    python学习心得第五章 1.冒泡排序: 冒泡是一种基础的算法,通过这算法可以将一堆值进行有效的排列,可以是从大到小,可以从小到大,条件是任意给出的. 冒泡的原理: 将需要比较的数(n个)有序的两个 ...

  8. Python第五章__模块介绍,常用内置模块

    Python第五章__模块介绍,常用内置模块 欢迎加入Linux_Python学习群  群号:478616847 目录: 模块与导入介绍 包的介绍 time &datetime模块 rando ...

  9. 0004-20180422-自动化第五章-python基础学习笔记

    内容回顾:1.数据类型 2.for和while循环 continue break #如下循环将怎么打印结果? for i in range(1,10): print(i) for i in range ...

随机推荐

  1. 软件包管理rpm和yum

    rpm的使用: 安装的包相关包信息会保存在/var/lib/rpm目录下的文件中 安装参数: -i install安装 -v 显示详细信息 -h 打印####号 -V 校验软件包,会到/var/lib ...

  2. OSI 七层模型以及TCP/IP模型

    OSI 七层模型 定义 OSI(Open System Interconnection)即开放式系统互联通信参考模型.该模型是国际标准化组织(ISO)制定的一个用于计算机或通信系统间互联的标准体系,一 ...

  3. 数据结构(C语言版)---线性表链式存储表示

    1.单链表:线性表的链式存储. 1)特点:用一组任意的存储单元存储数据元素(存储单元可以连续,也可以不连续),逻辑上相邻的元素存储位置不一定相邻. 2)结点包括两个域:数据域(存储数据元素信息).指针 ...

  4. DES原理及代码实现

    一.DES基础知识DES技术特点 DES是一种用56位密钥来加密64位数据的方法    DES采取了分组加密算法:明文和密文为64位分组长度    DES采取了对称算法:加密和解密除密钥编排不同外,使 ...

  5. mysql相关面试题(一)

    1.主键自增,姓名字段重复.删除重复的姓名数据,只留一条 -- Every derived table must have its own alias 子查询要起别名 -- 思路:分组后只会显示一条, ...

  6. Xss Game挑战

    前言 最新学习了下xss的更深入的东西,学习了一波浏览器解析机制和XSS向量编码的知识. 这里就些xss的练习题巩固知识 学习的话结合如下两篇文章看,从例子和基础原理层面都有: http://boba ...

  7. Spring5:Java Config

    @Configuration @Bean @ComponentScan @ImportResource 使用Java的方式配置spring,完全不使用spring配置文件,交给java来做! 两个注解 ...

  8. 感受python之美,python简单易懂的小例子

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 1 简洁之美 通过一行代码,体会Python语言简洁之美 2 Python ...

  9. php 判断是否手机端还是pc端

    来自:https://www.cnblogs.com/webenh/p/5621890.html 用手机访问PC端WWW域名的时候,自动判断跳转到移动端,用电脑访问M域名手机网站的时候,自动跳转到PC ...

  10. Python学习15之python内置六大标准类型

    1.六大标准类型:数值型,str,list,set,tuple,dic 2.数值型:int,float,bool,complex 3.区别: 1)数值型和str,tuple都是不可变类型 而list, ...