1.namedtuple: 生成可以使用名字来访问元素内容的tuple
>>> from collections import namedtuple >>> Point = namedtuple(‘Point‘, [‘x‘, ‘y‘]) >>> p = Point(1, 2) >>> p.x >>> p.y
2.OrderedDict: 有序字典
>>> from collections import OrderedDict >>> d = dict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)]) >>> d # dict的Key是无序的 {‘a‘: 1, ‘c‘: 3, ‘b‘: 2} >>> od = OrderedDict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)]) >>> od # OrderedDict的Key是有序的 OrderedDict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)])
3.defaultdict: 带有默认值的字典
from collections import defaultdict values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = defaultdict(list) for value in values: if value>66: my_dict[‘k1‘].append(value) else: my_dict[‘k2‘].append(value) defaultdict字典解决方法
时间: 2024-11-08 18:19:42