散列函数将输入映射到数字。
1.必须是一致的,apple每次都返回4。
2.不同的内容,映射不同的数字,输入什么都返回4就没有意义了。
散列,hash。
book = dict()book['apple'] = 0.67book['milk'] = 1.49book['avocado'] = 1.49print(book) #{'apple': 0.67, 'milk': 1.49, 'avocado': 1.49}print(book['apple']) #0.67
检测是否已经投票
voted = {}def check_voter(name): if voted.get(name): print ("kick them out!") else: voted[name] = True print ("let them vote!")check_voter("tom") # let them vote!check_voter("mike") # let them vote!check_voter("mike") # kick them out!
应用于缓存处理
cache = {}def get_page(url): if cache.get(url): print("缓存获取"); return cache[url] else: print("第一次获取"); data = get_data_from_server(url) cache[url] = data return datadef get_data_from_server(url): return url+"数据";print(get_page("cnblogs.com")); #第一次获取 cnblogs.com数据print(get_page("cnblogs.com")); #缓存获取 cnblogs.com数据