python中collections模块_Python的collections模块

python的collections模块

collections模块

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

常用方法:

elements():返回一个迭代器,每个元素重复计算的个数,如果一个元素的计数小于1,就会被忽略。

most_common([n]):返回一个列表,提供n个访问频率最高的元素和计数

subtract([iterable-or-mapping]):从迭代对象中减去元素,输入输出可以是0或者负数

update([iterable-or-mapping]):从迭代对象计数元素或者从另一个 映射对象 (或计数器) 添加。

>>> 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()

>>> 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

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值