ChainMap
from collections import ChainMap
car_parts = {'hood':500,'engine':500,'front_door':750}
car_options = {'A/C':1000,'Turbo':2500,'rollbar':300}
car_accessories = {'cover': 100, 'hood_ornament': 150, 'seat_cover': 99}
car_pricing = ChainMap(car_accessories, car_options, car_parts)
if __name__ == '__main__':
print(car_pricing)
print(car_pricing['hood'])ChainMap({'hood_ornament': 150, 'seat_cover': 99, 'cover': 100}, {'Turbo': 2500, 'A/C': 1000, 'rollbar': 300}, {'hood': 500, 'engine': 500, 'front_door': 750})
500
组合的字典当中不能有相同的健,遇到相同的健 只保留最后一个的值
上面例子中如果把
car_accessories = {'cover': 100, 'hood': 150, 'seat_cover': 99}
则输出ChainMap({'hood': 150, 'seat_cover': 99, 'cover': 100}, {'Turbo': 2500, 'A/C': 1000, 'rollbar': 300}, {'hood': 500, 'engine': 500, 'front_door': 750})
150
Counter
Counter能够计算出一个字符串中每个字符出现的次数,并以字典的形式返回
coding:utf-8
from collections import Counter
if name == 'main':
counter = Counter('superfluous')
print(counter)
print(counter['u'])
print(list(counter.elements())) #转成数组
print(counter.most_common(2)) #次数最多的前两位Counter({'u': 3, 's': 2, 'e': 1, 'f': 1, 'l': 1, 'o': 1, 'p': 1, 'r': 1})
3
['e', 'f', 'l', 'o', 'p', 's', 's', 'r', 'u', 'u', 'u']
[('u', 3), ('s', 2)]
defaultdict
The defaultdict will automatically assign zero as the value to any key it doesn’t already have in it.
defaultdict会把每个键的值都默认赋值0
coding:utf-8
from collections import defaultdict
sentence = "The red for jumped over the fence and to the zoo for food"
words = sentence.split(' ')
d = defaultdict(int) #值的类型是 int
for word in words:
d[word]+=1
print(d)defaultdict(
, {'and': 1, 'fence': 1, 'for': 2, 'food': 1, 'jumped': 1, 'over': 1, 'zoo': 1, 'to': 1, 'The': 1, 'the': 2, 'red': 1})
原始写法
def listtest():
my_list = [(1234, 100.23), (345, 10.45), (1234, 75.00),(345, 222.66), (678, 300.25), (1234, 35.67)]
reg_dict = {}
for acct_num,value in my_list:
if acct_num in reg_dict:
reg_dict[acct_num].append(value)
else:
reg_dict[acct_num] = [value]
print(reg_dict)
if __name__ == '__main__':
listtest()
def listtest():
my_list = [(1234, 100.23), (345, 10.45), (1234, 75.00),(345, 222.66), (678, 300.25), (1234, 35.67)]
d = defaultdict(list)
print(d)
for acct_num,value in my_list:
d[acct_num].append(value)
print(d)
print(d[345])
if __name__ == '__main__':
listtest()defaultdict(
, {})
defaultdict(, {345: [10.45, 222.66], 1234: [100.23, 75.0, 35.67], 678: [300.25]})
[10.45, 222.66]
结合lambda表达式
def lam():
animal = defaultdict(lambda:'Monkey')
animal['Sam'] = 'Tiger'
print(animal)
print(animal['Sam'])
print(animal['d'])
if __name__ == '__main__':
lam()defaultdict(
at 0x10433cc80>, {'Sam': 'Tiger'})
Tiger
Monkey
定义一个返回默认值为Monkey的lambda表达式。当输入一个没有定义过的键时,返回Monkey
deque
它提供了两端都可以操作的序列,这意味着,在序列的前后你都可以执行添加或删除操作
from collections import deque
import string
d = deque(string.ascii_lowercase)
print(d)
d.append('bork')
print(d)
d.appendleft('test')
print(d)
d.rotate(2)
print(d)
print(deque(list(d),5))deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'])
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'bork'])
deque(['test', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'bork'])
deque(['z', 'bork', 'test', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y'])
deque(['u', 'v', 'w', 'x', 'y'], maxlen=5)
namedtuple
namedtuple主要用来产生可以使用名称来访问元素的数据对象,通常用来增强代码的可读性。有点像其他语言中的结构体
coding:utf-8
from collections import namedtuple
变量名和namedtuple中的第一个参数一般保持一致,但也可以不一样
Parts = namedtuple('Parts', 'id_num desc cost amount')
Parts = namedtuple('Parts',['id_num', 'desc', 'cost', 'amount'])
auto_parts = Parts(id_num='1234',desc='Ford Engin',cost=1200.00,amount=10)
print(auto_parts.id_num)
print(auto_parts[2])
print(issubclass(Parts,tuple))1234
1200.0
True
OrderedDict
字典是没有顺序的,OrderedDict有顺序
coding:utf-8
from collections import OrderedDict
d = {'banana':3,'apple':4,'pear':1,'orange':2}print(d.items())
new_d = OrderedDict(sorted(d.items()))
print(new_d)
for key in new_d:
print(key,'-->',new_d[key])OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
('apple', '-->', 4)
('banana', '-->', 3)
('orange', '-->', 2)
('pear', '-->', 1)