from collections import defaultdict from collections import OrderedDict d = defaultdict(list) d[‘a‘].append(1) d[‘a‘].append(2) d[‘b‘].append(5) print(d) #di = dict(list) #di[‘b‘].append(11) #di[‘b‘].append(22) #di[‘c‘].append(55) #print(di) ds = defaultdict(set) ds[‘b‘].add(11) ds[‘b‘].add(22) ds[‘c‘].add(33) print(ds) do = OrderedDict() do[‘foo‘] = 1 do[‘far‘] = 2 do[‘coo‘] = 5 for key in do: print(key, do[key]) # 字典的运算 prices = { ‘IBM‘: 205.5, ‘APPLE‘: 500, ‘HP‘: 43, ‘FB‘: 88.3 } min_prices = min(zip(prices.values(), prices.keys())) print(min_prices) max_prices = max(zip(prices.values(), prices.keys())) print(max_prices) prices_sorted = sorted(zip(prices.values(), prices.keys())) print(prices_sorted) z1 = [1,2,3] z2 = [‘A‘,‘B‘,‘C‘] z3 = zip(z1, z2) print(list(z3)) z4 = zip(*zip(z1, z2)) print(list(z4)) x = [1,2] y = [‘a‘,‘b‘,‘c‘] print(list(zip(x,y))) #zip()配合*号操作符,可以将已经zip过的列表对象解压, 并且返回的是元祖 #使用zip和iterators生成滑动窗口 (n -grams) from itertools import islice def n_grams(a, n): z = (islice(a, i, None) for i in range(n)) return zip(*z) a = [1,2,3,4,5,6] print(‘(a,3):‘,list(n_grams(a,3))) print(‘(a,2):‘,list(n_grams(a,2))) print(‘(a,4):‘,list(n_grams(a,4))) # 使用zip反转字典 m = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4} print(‘m.items = ‘, m.items()) print(list(zip(m.values(), m.keys()))) md = dict(zip(m.values(), m.keys())) print(md)
时间: 2024-10-27 02:41:08