Python的collections模块

2021-02-19  本文已影响0人  牛二的Homework

python的collections模块

collections模块

Counter:字典的子类,提供了可哈希对象的计数功能

常用方法:

>>> import collections
>>> collections.Counter('hello python')
Counter({'h': 2, 'l': 2, 'o': 2, 'e': 1, ' ': 1, 'p': 1, 'y': 1, 't': 1, 'n': 1})
>>> collections.Counter('hello world hello python'.split())
Counter({'hello': 2, 'world': 1, 'python': 1})
>>> 
>>> c = collections.Counter('hello world hello python'.split())
>>> c
Counter({'hello': 2, 'world': 1, 'python': 1})
>>> c['hello']
2
>>> c.elements()
<itertools.chain object at 0x1029306d8>
>>> list(c.elements())
['hello', 'hello', 'world', 'python']
>>> c1 = collections.Counter('hello world'.split())
>>> c2 = collections.Counter('hello python'.split())
>>> c1
Counter({'hello': 1, 'world': 1})
>>> c2
Counter({'hello': 1, 'python': 1})
>>> c1.update(c2)
>>> c1
Counter({'hello': 2, 'world': 1, 'python': 1})
>>> c2
Counter({'hello': 1, 'python': 1})
>>> c1+c2
Counter({'hello': 3, 'python': 2, 'world': 1})
>>> c1.subtract(c2)
>>> c1
Counter({'hello': 1, 'world': 1, 'python': 0})
>>> c1 -c2

namedtuple 创建命名元组子类的工厂函数

三种定义命名元组的方法:第一个参数是命名元组的构造器(如下的:DN1,DN2,DN3)

>>> p1 = collections.namedtuple('DN1', ['name', 'age', 'height'])
>>> p2 = collections.namedtuple('DN2', 'name, age, height')
>>> p3 = collections.namedtuple('DN3', 'name age height')

# 实例化命名元组
>>> jason = p1('jason', 18, 180)
>>> jason
DN1(name='jason', age=18, height=180)
>>> jack = p2('jack',20,190)
>>> jack
DN2(name='jack', age=20, height=190)
>>> jason.name
'jason'
>>> jack.age
20
>>> 
上一篇下一篇

猜你喜欢

热点阅读