常用模块之collections模块(十七)

除python提供的内置数据类型(int、float、str、list、tuple、dict)外,collections模块还提供了其他数据类型:

  • 计数器(counter)
  • 有序字典(orderedDict)
  • 可命名元组(namedtuple)
  • 双向队列(deque)

在Python中,我们使用以下的代码导入collections模块:

import collections

判断目标是否为一个迭代器:

from collections.abc import Iterator

#判断字符串对象是不是一个迭代器,输出False
print(isinstance("hello", Iterator))
#判断iter对象是不是一个迭代器,输出True
print(isinstance(iter('hello'), Iterator))

以上代码输出的实列:

Python武器库开发-常用模块之collections模块(十七)_开发语言

判断目标是不是一个生成器:

from collections.abc import Generator

#判断目标是不是一个生成器,输出False
print(isinstance(iter('hello'), Generator))
#创建一个生成器
Generators = (i ** 2 for i in range(10))
# 判断目标是不是一个生成器,输出True
print(isinstance(Generators,Generator))

以上代码输出的实列:

Python武器库开发-常用模块之collections模块(十七)_python_02

对字典进行排序:

字典的本质上是哈希表,根源上来讲是无序的,但是OrderedDict这个对象可以保持插入字典的有序

from collections import OrderedDict
import json

#创建OrderedDict对象的有序字典
dict = OrderedDict()
dict["apple"] = 1
dict["google"] = 2
dict["ms"] = 3
dict["alibaba"] = 4

#遍历字典
for i in dict:
    print(i,dict[i])
print("--------------")
#输出字典的json序列化格式
print(json.dumps(dict))

以上代码输出的实列:

Python武器库开发-常用模块之collections模块(十七)_python_03

命名元组:

它可以通过索引来访问数据,能够迭代,可以通过属性名来进行访问

from collections import namedtuple


Point = namedtuple('Point',["x","y"])
p = Point(10, 12)
#通过属性名来进行访问
print(p.x)
print(p.y)

以上代码输出的实列:

Python武器库开发-常用模块之collections模块(十七)_网络安全_04

计数器:

计数器可以统计可迭代对象里面的每一个元素出现的次数

from collections import Counter

c = Counter("http://www.baidu.com")
print(c)

以上代码输出的实列:

Python武器库开发-常用模块之collections模块(十七)_服务器_05

可以看到”w“字符出现了3次,”t“字符出现了两次,"/"出现了两次…使用most_common可以更详细的列出我们想要的数据,比如我们想要知道前三个数据的出现次数:

from collections import Counter


c = Counter("http://www.baidu.com")
print(c.most_common(3))

以上代码输出的实列:

Python武器库开发-常用模块之collections模块(十七)_网络安全_06