Python collections 拾遗

class Counter(dict): 继承dict类

  • 初始化:
from collections import Counter
c = Counter()                   # a new, empty counter
print(c)                        # Counter()
c = Counter('gallahad')         # a new counter from an iterable
print(c)                        # Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
c = Counter({'a': 4, 'b': 2})   # a new counter from a mapping
print(c)                        # Counter({'a': 4, 'b': 2})
c = Counter(a=4, b=2)           # a new counter from keyword args
print(c)                        # Counter({'a': 4, 'b': 2})
  • most_common() 出现频率最高的n个
print(Counter('abcdeabcdabcaba').most_common(3)) 
# [('a', 5), ('b', 4), ('c', 3)]
  • elements() 返回一个迭代器,每个元素出现几次就是几次,如果次数是0或负数,则忽略
print(Counter('ABCABC').elements())           # 返回的是迭代器
print(sorted(Counter('ABCABC').elements()))   
# ['A', 'A', 'B', 'B', 'C', 'C']
  • update()更新

c = Counter('which')
# Counter({'h': 2, 'w': 1, 'i': 1, 'c': 1})
print(c)
c.update('witch')     
# Counter({'h': 3, 'w': 2, 'i': 2, 'c': 2, 't': 1})
print(c)
d = Counter('watch')
c.update(d)           
# Counter({'h': 4, 'w': 3, 'c': 3, 'i': 2, 't': 2, 'a': 1})
print(c)
  • subtract相减
c = Counter('which')
# Counter({'h': 2, 'w': 1, 'i': 1, 'c': 1})
print(c)
c.subtract('witch')
# Counter({'h': 1, 'w': 0, 'i': 0, 'c': 0, 't': -1})
print(c)
c.subtract(Counter('watch'))
# Counter({'h': 0, 'i': 0, 'w': -1, 'c': -1, 'a': -1, 't': -2})
print(c)

class OrderedDict(dict): 有序字典

  • popitem() 删除最后一个
  • pop(key) 删除对应key的元素
from collections import OrderedDict

dic = {'a': 1, 'b': 2, 'c': 3, 'd':4 }
dic = OrderedDict(dic)
print(dic)   # OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
dic.popitem()
print(dic)   # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
dic.popitem()
print(dic)   # OrderedDict([('a', 1), ('b', 2)])
dic.popitem()
dic.popitem()
print(dic)   # OrderedDict()
dic.popitem()  # KeyError: 'dictionary is empty'



dic = {'a': 1, 'b': 2, 'c': 3, 'd':4 }
dic = OrderedDict(dic)
print(dic)   # OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
dic.pop('b') # OrderedDict([('a', 1), ('c', 3), ('d', 4)])
print(dic)
dic.pop('e') # KeyError: 'e'
  • move_to_end() 移动指定元素到末尾或开始
dic = {'a': 1, 'b': 2, 'c': 3, 'd':4 }
dic = OrderedDict(dic)
print(dic)   # OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
dic.move_to_end('b')
print(dic)   # OrderedDict([('a', 1), ('c', 3), ('d', 4), ('b', 2)])
dic.move_to_end('b', False)  # last = False, move to beginning
# OrderedDict([('b', 2), ('a', 1), ('c', 3), ('d', 4)])
print(dic)
  • items()
  • values()
  • keys()
dic = {'a': 1, 'b': 2, 'c': 3, 'd':4 }
dic = OrderedDict(dic)
print(dic)   # OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
print(dic.keys())  # odict_keys(['a', 'b', 'c', 'd'])
print(dic.values()) # odict_values([1, 2, 3, 4])
print(dic.items())  # odict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
  • setdefault()
  • fromkeys()
dic = {'a': 1, 'b': 2, 'c': 3, 'd':4 }
dic = OrderedDict(dic)
print(dic)   # OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
dic.setdefault('e')
print(dic)
dic.setdefault('f', 6)
print(dic)

seq = ('name', 'age', 'sex')

dict = OrderedDict.fromkeys(seq)
print("New Dictionary : %s" %  str(dict))

dict = OrderedDict.fromkeys(seq, 10)
print("New Dictionary : %s" %  str(dict))

默认字典(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)

print(my_dict)
# defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})

可命名元组(namedtuple)


from collections import namedtuple
Mytuple = namedtuple('Mytuple', ['x', 'y', 'z'])
temp1 = Mytuple(x=1, y=2, z=3)
print(temp1[1])    # 2
print(temp1.y)     # 2

如果遇到Python关键字或者有重复元素名时,用重命名模式自动进行重命名

import collections
with_class = collections.namedtuple('Person', 'name age class gender', rename=True)
print(with_class._fields) # ('name', 'age', '_2', 'gender')
two_ages = collections.namedtuple('Person', 'name age gender age', rename=True)
print(two_ages._fields) # ('name', 'age', 'gender', '_3')

双向队列(deque)


from collections import deque
d = deque([1, 2, 3, ])
print(d)                   # deque([1, 2, 3])

d.append(4)                # deque([1, 2, 3, 4])
print(d)
d.appendleft(0)            # deque([0, 1, 2, 3, 4])
print(d)

print(d.index(3))          # 3
print(d.index(3, 2, 4))    # 3
# print(d.index(5))        # ValueError: 5 is not in deque

d.insert(2, 'a')           # deque([0, 1, 'a', 2, 3, 4])
print(d)
d.insert(10, 'b')          # deque([0, 1, 'a', 2, 3, 4, 'b'])
print(d)

d.extend([5, 6, 7, ])      # deque([0, 1, 2, 3, 4, 5, 6, 7])
print(d)
d.extendleft([-3, -2, -1, ])
print(d)                   # deque([-1, -2, -3, 0, 1, 2, 3, 4, 5, 6, 7])

print(d.pop())             # 7
print(d)                   # deque([-1, -2, -3, 0, 1, 'a', 2, 3, 4, 'b', 5, 6])
print(d.popleft())         # -1
print(d)                   # deque([-2, -3, 0, 1, 'a', 2, 3, 4, 'b', 5, 6])

print(d.remove('a'))       # None
print(d)                   # deque([-2, -3, 0, 1, 2, 3, 4, 'b', 5, 6])
# d.remove('c')              # ValueError: deque.remove(x): x not in deque

print(d.reverse())         # None
print(d)                   # deque([6, 5, 'b', 4, 3, 2, 1, 0, -3, -2])

d.rotate()
print(d)                   # deque([-2, 6, 5, 'b', 4, 3, 2, 1, 0, -3])
d.rotate(2)
print(d)                   # deque([0, -3, -2, 6, 5, 'b', 4, 3, 2, 1])
d.rotate(-1)
print(d)                   # deque([-3, -2, 6, 5, 'b', 4, 3, 2, 1, 0])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值