python 高級編程與異步IO併發編程(六)深刻python的set和dict

6-1 dict的abc繼承關係

from collections import Mapping,MutableMapping
#dict屬於mapping類型
a={}
print (isinstance(a,MutableMapping))


複製代碼

6-2 dict的經常使用方法

a=dict()
a={"bobby1":{"company":"imooc"},"bobby1":{"company":"imooc"}}
#clear
#a.clear()
#pass

#copy,返回淺拷貝
new_dict = a.copy()
new_dict["bobby1"]["company"]="imooc3"

#copy,返回深拷貝
import copy
new_dict=copy.deepcopy(a)
new_dict["bobby1"]["company"]="imooc3"

#formkeys
new_list=["bobby1","bobby2"]

new_dict=dict.fromkeys(new_list,{"company":imooc})
value=new_dict.get("bobby",{})

複製代碼

6-3 dict的子類

#不建議繼承set和dictpython

class Mydict(dict):
    def __setitem__(self,key,value):
        super().__setitem__(key,value*2)
        
my_dict=Mydict(one=1)
my_dict["one"] =1
print(my_dict)

from collections import UserDict

class Mydict(UserDict):
    def __setitem__(self,key,value):
        super().__setitem__(key,value*2)
        
my_dict=Mydict(one=1)
#my_dict["one"] =1
print(my_dict)

from collections import defaultdict 
my_dict=defaultdict(dict)
my_value=my_dict["bobby"]
pass

複製代碼

6-4 set和frozenset

#set 集合 fronzenset(不可變集合)無序,不重複編程

s = set('abcde')
s = set(['a','b','c','d','e'])
s={'a','b'}
print(type(s))

s = fornzenset('abcde') #fronzenset 能夠做爲dict的key

#向set添加數據
s.add()
another_set=set("def")
s.update(another_set)
re_set=s.defference(another_set)
re_set = s-another_set
# / & - #集合運算
#set性能很高
print (s.issubset(re_set))
if "c" in re_set:
    print("i am in set")
複製代碼

6-5 dict和set的實現原理

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)
    last_time = find_test(all_data, target_data)
    #dict查找的性能遠遠大於list
    #在list中隨着list數據的增大,查找時間會增大
    #在dict中隨着dict的增大,查找時間不會增大
    print(last_time)

#dict 的key或者set的值,都必須是能夠hash的
#不可變對象 都是可哈希的,str,fronzenset,tuple,本身實現的類,能夠實現__hash__方法
#2.dict的內存花銷大,可是查詢速度快本身定義的對象或者python內部的對象都是用dict包裝的
#3.dict的存儲順序和元素的添加順序有關
#4.添加數據有可能改變已有數據的順序
複製代碼

6-6 本章小結

python基於協議編程的,dict經常使用的用法,dict的子類,set和fronzenset,dict背後的哈希表與特性.bash

相關文章
相關標籤/搜索