探索 Python 的 Collections 模块

PythonBeginner
立即练习

介绍

在本教程中,我们将探索 Python 内置的 collections 模块。collections 模块是一个强大的库,提供了多种容器数据类型,这些类型扩展了 Python 内置容器(如列表、元组和字典)的功能。

NamedTuple

namedtuple 是元组的一个子类,提供了命名字段,使代码更具可读性和自文档化。让我们在 named_tuple.py 中创建一个 namedtuple 来表示二维空间中的一个点:

## Import collections
from collections import namedtuple

## Define a namedtuple type Point with x and y properties
Point = namedtuple('Point', ['x', 'y'])

## Create a Poinit object
p = Point(1, 2)

## Retrieve the properties of point
print(p.x)
print(p.y)

然后,请在终端中运行脚本:

python named_tuple.py

输出:

1
2

Counter

Counterdict 的一个子类,用于统计集合中元素的出现次数。让我们在 counter.py 中创建一个 Counter 对象来统计字符串中字符的出现次数:

from collections import Counter

text = "hello, world!"
## Gets the number of occurrences of the elements in the collection and returns them as a dictionary
char_count = Counter(text)

print(char_count)

然后,请在终端中运行脚本:

python counter.py

输出:

Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ',': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1})

OrderedDict

OrderedDictdict 的一个子类,它维护元素插入的顺序。让我们在 ordered_dict.py 中创建一个 OrderedDict 并添加一些键值对:

from collections import OrderedDict

## Initialdefining OrderedDict
od = OrderedDict()

## Insert in key-value pairs
od['a'] = 1
od['b'] = 2
od['c'] = 3

## Iterate over the key-value pairs and print out the contents
for key, value in od.items():
    print(key, value)

然后,请在终端中运行脚本:

python ordered_dict.py

输出:

a 1
b 2
c 3

DefaultDict

Defaultdict(int)

DefaultDictdict 的一个子类,它为不存在的键提供默认值。让我们在 default_dict1.py 中创建一个默认值为 0DefaultDict,并统计句子中单词的出现次数:

from collections import defaultdict

sentence = "the quick brown fox jumps over the lazy dog"
word_count1 = defaultdict(int)

for word in sentence.split():
    ## Count the occurrences of words
    word_count1[word] += 1

print(dict(word_count1))

然后,请在终端中运行脚本:

python default_dict1.py

输出:

{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}

如果我们不使用 DefaultDict,代码将如下所示:

sentence = "the quick brown fox jumps over the lazy dog"
result = {}

for word in sentence.split():
    if word in result:
        result[word] += 1
    else:
        result[word] = 1

print(result)

Defaultdict(list)

接下来,让我们在 default_dict2.py 中创建一个默认值为 []DefaultDict,并存储每个字母对应的数字:

from collections import defaultdict

data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
word_count2 = defaultdict(list)

for (key,value) in data:
    ## Store the number in each letter
    word_count2[key].append(value)

print(dict(word_count2))

然后,请在终端中运行脚本:

python default_dict2.py

输出:

{'a': [1, 1, 3], 'b': [1, 2, 3]}

如果我们不使用 DefaultDict,代码将如下所示:

data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
result = {}

for (key, value) in data:
    if key in result:
        result[key].append(value)
    else:
        result[key] = [value]

print(result)

Defaultdict(set)

最后,让我们在 default_dict3.py 中创建一个默认值为 set()DefaultDict,并存储每个字母对应的不重复数字:

from collections import defaultdict

data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
word_count3 = defaultdict(set)

for (key,value) in data:
    ## Stores the number that is not repeated in each letter
    word_count3[key].add(value)

print(dict(word_count3))

然后,请在终端中运行脚本:

python default_dict3.py

输出:

{'a': {1, 3}, 'b': {1, 2, 3}}

如果我们不使用 DefaultDict,代码将如下所示:

data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
result = {}

for (key, value) in data:
    if key in result:
        result[key].add(value)
    else:
        result[key] = {value}

print(result)

Deque

deque(双端队列)是栈和队列的泛化,支持从两端快速 O(1) 的添加和删除操作。让我们在 deque.py 中创建一个 deque 并执行一些操作:

from collections import deque

d = deque([1, 2, 3, 4, 5])

## Append to the right
d.append(6)
print("Append to the right:", d)

## Append to the left
d.appendleft(0)
print("Append to the left:", d)

## Pop from the right
right_element = d.pop()
print("The right element:", right_element)
print("Pop from the right:", d)

## Pop from the left
left_element = d.popleft()
print("The left element:", left_element)
print("Pop from the left:", d)

## Rotate the deque
d.rotate(2)
print("Rotate clockwise the deque:", d)

d.rotate(-2)
print("Rotate counterclockwise the deque:", d)

然后,请在终端中运行脚本:

python deque.py

输出:

Append to the right: deque([1, 2, 3, 4, 5, 6])
Append to the left: deque([0, 1, 2, 3, 4, 5, 6])
The right element: 6
Pop from the right: deque([0, 1, 2, 3, 4, 5])
The left element: 0
Pop from the left: deque([1, 2, 3, 4, 5])
Rotate clockwise the deque: deque([4, 5, 1, 2, 3])
Rotate counterclockwise the deque: deque([1, 2, 3, 4, 5])

总结

在本教程中,我们介绍了 collections 模块提供的主要类,包括 namedtupleCounterOrderedDictDefaultDictdeque。这些类可以用于各种任务,是 Python 工具包中的强大补充。