admin 管理员组

文章数量: 1086019


2024年4月30日发(作者:documents怎么关闭扣费)

collections在python的用法

在Python中,`collections`模块提供了许多有用的集合类,用于处理各种数据

结构和数据类型。以下是几个常用的类及其用法:

1. `Counter`:用于计数可哈希对象的出现次数。可以是列表、字符串、字典等。

例子:

python

from collections import Counter

lst = ['a', 'b', 'a', 'c', 'b', 'a']

counter = Counter(lst)

print(counter) # 输出: Counter({'a': 3, 'b': 2, 'c': 1})

2. `defaultdict`:默认字典,用于创建一个键不存在时有默认值的字典。需要传

递一个工厂函数作为参数,用于提供默认值。例子:

python

from collections import defaultdict

d = defaultdict(int)

print(d['a']) # 输出: 0

3. `deque`:双端队列,支持从两端高效地添加和删除元素。可以高效地实现队

列和栈的操作。例子:

python

from collections import deque

d = deque()

('a') # 从右端添加元素

left('b') # 从左端添加元素

print(d) # 输出: deque(['b', 'a'])

4. `OrderedDict`:有序字典,可以按照添加元素的顺序进行迭代。例子:

python

from collections import OrderedDict

d = OrderedDict()

d['a'] = 1

d['b'] = 2

d['c'] = 3

print(d) # 输出: OrderedDict([('a', 1), ('b', 2), ('c', 3)])

5. `namedtuple`:命名元组,用于创建具有字段名称的元组。可以通过字段名

或索引访问元组中的元素。例子:

python

from collections import namedtuple

Person = namedtuple('Person', ['name', 'age'])

p = Person('Alice', 25)

print() # 输出: Alice

还有其他许多在`collections`模块中定义的集合类,如`ChainMap`、`Counter`、

`namedtuple`等,可以根据具体需求选择使用。


本文标签: 用于 元素 字典