首页 > 代码库 > Python,collections模块

Python,collections模块

    对collections相关方法进行学习和测试:

# coding=utf-8

"""
testCollections.py
对collections集合模块进行实践和测试
"""

import collections
import unittest

class TestCollections(unittest.TestCase):
    
    def test_namedtuple(self):
        """
        namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
        用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用
        """
        job_type = collections.namedtuple(job_type, [H, M, L])
        job = job_type(, , )
        self.assertEqual(, job.H)
        self.assertEqual(, job.M)
        self.assertEqual(, job.L)
        point = collections.namedtuple(point, [x, y])
        p = point(1,2)
        self.assertEqual(1, p.x)
        self.assertEqual(2, p.y)

    def test_deque(self):
        """
        deque是为了高效实现插入和删除操作的双向列表
        """
        que = collections.deque([A,1,3,"B"])
        # 添加
        que.append("M")
        self.assertEqual("M", que[-1])
        # 删除
        res = que.pop()
        self.assertEqual("M", res)
        # 从左边添加元素
        que.appendleft("L")
        self.assertEqual("L", que[0])
        # 从左边删除
        self.assertEqual("L", que.popleft())

    def test_defaultdict(self):
        """
        defaultdict:Key不存在时返回默认值
        """
        default_dict = collections.defaultdict(lambda : "N/A")
        default_dict[name] = xiaoshitoutester
        default_dict[job] = tester
        self.assertEqual(xiaoshitoutester, default_dict[name])
        self.assertEqual(tester, default_dict[job])
        self.assertEqual(N/A, default_dict[age])

    def test_counter(self):
        """Counter:统计字符出现的次数"""
        str_example = "xiaoshitoutester"
        # list_example = [‘A22222‘,1,3,"B"]
        c = collections.Counter()
        for ch in str_example:
            c[ch] += 1
        self.assertEqual(3, c[t])



if __name__ == __main__:
      unittest.main()

 

Python,collections模块