python认识collections模块

collections模块提供高性能的容器数据类型,包括defaultdict、OrderedDict、namedtuple和deque等。defaultdict在字典中默认添加键值对,LeetCode问题49可用于加深理解。OrderedDict保持插入顺序,namedtuple为带命名字段的元组。deque是双向列表,常用于队列操作,如queue.Queue、collections.deque和multiprocessing.Manager().Queue(),并提供了多种方法进行操作。Counter是计数器,用于统计元素出现次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

collections是Python内建的集合模块
High-performance container datatypes

This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers,dict,list,set,and tuple.
官方文档传送门


替代类型解释

1,defaultdict

意义:
 1,通常通过Key访问字典,Key不存在,会引发‘KeyError’异常
 2,为了不发生异常,在没有Key的情况下,默认增加一个对应Key-Value

>>> dict={'a':1}
>>> dict['b']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'b'
>>> dict.update(b=2)
>>> dict['b']
2
>>> 

下面的例子由defaultdict构造,value=int,不会返回错误,默认构造一个Key=Value

>>> ddict=collections.defaultdict(int)
>>> ddict['a']
0

Leetcode.49

为了加深理解,我们来看这道题

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

说明:

    所有输入均为小写字母。
    不考虑答案输出的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解:

def groupAnagrams(self, strs):
        #指定字典的值为列表
        ans =defaultdict(list)
        for str in strs:
            #字典的值不能位列表,sorted(str)之后为列表,改为元祖即可
            ans[tuple(sorted(str))].append(str)

        return  ans.values()

2,OrderedDict

记录插入顺序的字典

3,namedtuple

命名元祖
Factory Function for Tuples with Named Fields

传送门

    from collections import namedtuple
     
    # 定义一个namedtuple类型User,并包含name,sex和age属性。
    User = namedtuple('User', ['name', 'sex', 'age'])
     
    # 创建一个User对象
    user = User(name='kongxx', sex='male', age=21)
     
    # 也可以通过一个list来创建一个User对象,这里注意需要使用"_make"方法
    user = User._make(['kongxx', 'male', 21])
     
    print(user)
    # User(name='user', sex='male', age=21)
     
    # 获取用户的属性
    print(user.name)
    print(user.sex)
    print(user.age)
     
    # 修改对象属性,注意要使用"_replace"方法
    user = user._replace(age=22)
    print(user)
    # User(name='user', sex='male', age=22)
     
    # 将User对象转换成字典,注意要使用"_asdict"
    print(user._asdict())
    # OrderedDict([('name', 'kongxx'), ('sex', 'male'), ('age', 22)])

4,deque

collections.deque()双向列表
queue.Queue()单向队列
multiprocessing.Queue()单向队列,用于多进程间的通信

4.1 queue.Queue

FIFO
常用方法:
Queue.Queue(maxsize=0) FIFO, 如果maxsize小于1就表示队列长度无限
Queue.LifoQueue(maxsize=0) LIFO, 如果maxsize小于1就表示队列长度无限
Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回True,反之False
Queue.full() 如果队列满了,返回True,反之False
Queue.get([block[, timeout]]) 读队列,timeout等待时间
Queue.put(item, [block[, timeout]]) 写队列,timeout等待时间
Queue.queue.clear() 清空队列

4.2 collections.deque

常用方法

append(x): Add x to the right side of the deque.
appendleft(x): Add x to the left side of the deque.
clear(): Remove all elements from the deque leaving it with length 0.
count(x): Count the number of deque elements equal to x.
extend(iterable): Extend the right side of the deque by appending elements from the iterable argument.
extendleft(iterable) Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.
pop(): Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.
popleft(): Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.
remove(value): Remove the first occurrence of value. If not found, raises a ValueError.
reverse(): Reverse the elements of the deque in-place and then return None.
rotate(n=1): Rotate the deque n steps to the right. If n is negative, rotate to the left.
 When the deque is not empty, rotating one step to the right is equivalent to d.appendleft(d.pop()), and rotating one step to the left is equivalent to d.append(d.popleft()).

Deque objects also provide one read-only attribute:
maxlen: Maximum size of a deque or None if unbounded.

>>> from collections import deque
>>> d = deque('ghi')                 # make a new deque with three items
>>> for elem in d:                   # iterate over the deque's elements
...     print elem.upper()
G
H
I

>>> d.append('j')                    # add a new entry to the right side
>>> d.appendleft('f')                # add a new entry to the left side
>>> d                                # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'
>>> list(d)                          # list the contents of the deque
['g', 'h', 'i']
>>> d[0]                             # peek at leftmost item
'g'
>>> d[-1]                            # peek at rightmost item
'i'

>>> list(reversed(d))                # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d                         # search the deque
True
>>> d.extend('jkl')                  # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1)                      # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1)                     # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d))               # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear()                        # empty the deque
>>> d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in -toplevel-
    d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc')              # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])

4.3 multiprocessing.Manager().Queue()

同queue.Queue()大同小异,这里主要作为进程间通信的一种手段

5,Counter

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.
字典的子类,一种特殊字典,value必须位整数 ,可以是0或负数

>>> c=collections.Counter('abdrdasdf')
>>> print(c)
Counter({'d': 3, 'a': 2, 'b': 1, 'r': 1, 's': 1, 'f': 1})
#统计字符出现的次数,以字典Key-Values的形式保存
>>>print(c.most_common(2))
[('d', 3), ('a', 2)]
#显示前两个
>>> print(list(c.elements()))
['a', 'a', 'b', 'd', 'd', 'd', 'r', 's']
#显示所有key×values,所以0和负数的情况会不显示
#subtract
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值