# python三十六库之collections

3 篇文章 0 订阅

### Collections

• namedtuple

• deque

• Counter

• OrderedDict

• defaultdict

#### Counter


In [70]: for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...:     c[word] += 1
...:

In [71]: c
Out[71]: Counter({'blue': 3, 'green': 1, 'red': 2})



Counter内建方法分别为 elements() most_common() subtract()

##### elements


In [132]: c = Counter(a=4, b=2, c=0, d=-2)

In [133]: list(c.elements())
Out[133]: ['a', 'a', 'a', 'a', 'b', 'b']


##### most_common


Out[134]: [('a', 5), ('r', 2), ('b', 2)]

Out[135]: [('a', 5), ('r', 2), ('b', 2), ('c', 1)]


##### subtract


In [136]: c = Counter(a=4, b=2, c=0, d=-2)

In [137]: d = Counter(a=1, b=2, c=3, d=4)

In [138]:  c.subtract(d)

In [139]: c
Out[139]: Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})



#### deque

• append()

• appendleft()

• clear()

• count()

• extend()

• extendletf()

• pop()

• popleft()

• remove() deque中的元素向右移动n个位置。如果n是负数的向左移动

• reverse()

• rotate()

• maxlen()


In [142]: d = deque('ghi')

In [143]: d.rotate(1)

In [144]: d
Out[144]: deque(['i', 'g', 'h'])

In [145]: d.rotate(-3)

In [146]: d
Out[146]: deque(['i', 'g', 'h'])

In [147]: d.rotate(-2)

In [148]: d
Out[148]: deque(['h', 'i', 'g'])



#### defaultdict

defaultdict是内置的dict类的一个子类。 它覆盖一个方法并添加一个可写的实例变量.


In [161]: s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

In [162]: d = defaultdict(list)

In [163]: for k, v in s:
...:     d[k].append(v)
...:

In [164]: d.items()
Out[164]: [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

In [173]: s = [('yellow', {'k': 1}), ('blue', {'v': 2}), ('red', {'p': 3})]

In [174]:

In [174]: for k, v in s:
...:     d[k] = v
...:

In [176]: d.items()
Out[176]: [('blue', {'v': 2}), ('red', {'p': 3}), ('yellow', {'k': 1})]



#### namedtuple


In [178]:  Point = namedtuple('Point', ['x', 'y'], verbose=True)

In [179]: p = Point(11, 22)

In [180]: p.x
Out[180]: 11

In [181]: p.y
Out[181]: 22



#### Orderedict


In [226]: d
Out[226]: OrderedDict([('orange', 2), ('pear', 1), ('banana', 3), ('apple', 4)])

In [227]: b = dict({'banana': 3, 'apple':4, 'pear': 1, 'orange': 2})

In [229]: b
Out[229]: {'apple': 4, 'banana': 3, 'orange': 2, 'pear': 1}

In [230]: d
Out[230]: OrderedDict([('orange', 2), ('pear', 1), ('banana', 3), ('apple', 4)])



• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
11-16 1541
06-26 1685
10-09 493
10-25 865
09-13 504
09-14 548
09-12 1214
09-13 1544
09-16 595
09-16 609

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。