python collections模块

python collections提供了一些数据类型的扩展,使用起来非常方便

Counter类

Counter类是一个计数器类,继承于字典类,表示对象和相应的计数
常见的一个应用就是词频的统计

from collection import Counter
import re


if __name__ == "__main__":
    path = "/usr/lib/python3.5/LICENSE.txt"
    words = re.findall("\w+", open(path).read().lower())
    # most_common(n=None) 返回频率最高的前n个组成的字典
    print(Counter(words).most_common(10))

[(‘the’, 80), (‘or’, 78), (‘1’, 66), (‘of’, 61), (‘to’, 50), (‘and’, 48), (‘python’, 46), (‘in’, 38), (‘any’, 37), (‘license’, 37)]

OrderedDict类

默认的字典是以Hash表存储的,进行迭代遍历的时候,没有顺序性。collection.OrderedDict类提供了可以顺序遍历的字典

from collections import OrderedDict

d = OrderedDict()  # 建立一个OrderedDict对象
d["name"] = "hui"
d["age"] = 20
d["gender"] = "M"
for k, v in d.items():
    print("{}: {}".format(str(k), str(v)))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值