19 Python Collections 模块详解

19 Python Collections 模块详解

Python 的 collections 模块提供了一些额外的数据结构,比内建的数据结构更为灵活、高效。下面是对 collections 模块的详细介绍,涵盖其常用类型和应用示例。

1. namedtuple()

namedtuple() 是一种工厂函数,用于创建一个元组子类,它允许你使用命名字段来访问元组元素,提高代码的可读性。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
from collections import namedtuple

# 创建一个名为 Point 的命名元组
Point = namedtuple('Point', ['x', 'y'])

# 创建一个 Point 实例
p = Point(10, 20)

# 访问字段
print(p.x) # 输出: 10
print(p.y) # 输出: 20

2. deque

deque 是双端队列,支持在两端高效地添加和删除元素,比使用列表更快。

用法示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from collections import deque

# 创建一个 deque
d = deque()

# 从右侧添加元素
d.append(1)
d.append(2)

# 从左侧添加元素
d.appendleft(0)

# 删除右侧元素
d.pop() # 输出: 2

# 删除左侧元素
d.popleft() # 输出: 0

print(d) # 输出: deque([1])

3. Counter

Counter 是用于计数哈希表的子类,特别适合处理可哈希对象的计数统计。

计数示例:

1
2
3
4
5
6
7
8
9
10
from collections import Counter

# 创建一个 Counter
c = Counter(['a', 'b', 'a', 'c', 'b', 'b'])

# 获取元素的计数
print(c) # 输出: Counter({'b': 3, 'a': 2, 'c': 1})

# 获取最常见的元素
print(c.most_common(1)) # 输出: [('b', 3)]

4. OrderedDict

OrderedDict 是一个 dict 的子类,它记住了元素添加的顺序。在 Python 3.7 及之后,普通的字典也保持插入顺序,但 OrderedDict 提供了一些额外的方法。

使用示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from collections import OrderedDict

# 创建一个 OrderedDict
od = OrderedDict()

# 添加元素
od['a'] = 1
od['b'] = 2
od['c'] = 3

# 输出: Ordered dict保持元素的添加顺序
print(od) # 输出: OrderedDict([('a', 1), ('b', 2), ('c', 3)])

# popitem() 方法可以移除最后一个元素
od.popitem()
print(od) # 输出: OrderedDict([('a', 1), ('b', 2)])

5. defaultdict

defaultdict 提供了一个默认值,用于处理字典中未定义的键,以避免 KeyError

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
from collections import defaultdict

# 创建一个 defaultdict,默认值为列表
d = defaultdict(list)

# 向默认字典添加元素
d['fruit'].append('apple')
d['fruit'].append('banana')
d['vegetable'].append('carrot')

# 输出: defaultdict(<class 'list'>, {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']})
print(d)

总结

collections 模块极大地增强了 Python 的数据结构能力,提供了更方便和高效的方法来处理各种数据。在实际开发中,应根据需求选择合适的数据结构,以提高程序的性能和可读性。

函数的参数与返回值

函数的参数与返回值

在学习 Python 的过程中,理解函数的参数与返回值是非常重要的。这部分内容将帮助你掌握函数如何接收输入和如何返回输出。

1. 函数的定义

在 Python 中,使用 def 关键字定义一个函数。例如:

1
2
def greet(name):
print(f"Hello, {name}!")

这里 greet 是函数的名称,name 是函数的参数。

2. 函数的参数

2.1. 位置参数

位置参数是在调用函数时按照位置传递给函数的参数。例如:

1
2
3
4
5
def add(a, b):
return a + b

result = add(5, 3) # 5 和 3 是位置参数
print(result) # 输出 8

2.2. 默认参数

可以为参数设定默认值,如果在调用函数时不传递该参数,则使用默认值。例如:

1
2
3
4
5
def greet(name="Guest"):
print(f"Hello, {name}!")

greet() # 使用默认参数,输出 "Hello, Guest!"
greet("Alice") # 输出 "Hello, Alice!"

2.3. 可变参数

通过 *args 可以接收任意数量的位置参数。args 是一个元组。

1
2
3
4
5
def sum_all(*args):
return sum(args)

result = sum_all(1, 2, 3, 4) # args=(1, 2, 3, 4)
print(result) # 输出 10

使用 **kwargs 可以接收任意数量的关键字参数。kwargs 是一个字典。

1
2
3
4
5
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_info(name="Alice", age=25) # 输出 name: Alice 和 age: 25

3. 返回值

使用 return 语句来返回函数的值。函数可以返回一个值,也可以返回多个值(以元组形式返回)。

3.1. 返回单个值

1
2
3
4
5
def square(x):
return x * x

result = square(4)
print(result) # 输出 16

3.2. 返回多个值

可以通过逗号分隔返回多个值,这些值会包装成一个元组。

1
2
3
4
5
def operations(x, y):
return x + y, x - y, x * y, x / y

add, sub, mul, div = operations(10, 5) # 解构赋值
print(add, sub, mul, div) # 输出 15 5 50 2.0

4. 小结

在 Python 中,函数的参数和返回值是构建函数的重要部分:

  • 参数可以是位置参数、默认参数、可变参数等。
  • 返回值可以是单个值或多个值(元组)。

理解这一点,可以让你更灵活地使用 Python 编写函数!继续练习,将会让你更加熟悉这些概念。

`itertools` 与 `functools` 模块

`itertools` 与 `functools` 模块

在 Python 中,itertoolsfunctools 模块提供了丰富的工具来处理迭代和函数式编程。本文将详细介绍这两个模块的使用方法,并通过代码示例帮助你更好地理解它们。

一、itertools 模块

itertools 模块提供了函数用来创建和操作迭代器,这些函数可以帮助你高效地处理数据流。

1. count(start=0, step=1)

count 是一个无限迭代器,产生从 start 开始的数字,每次递增 step

1
2
3
4
5
6
import itertools

counter = itertools.count(start=1, step=2)
print(next(counter)) # 输出:1
print(next(counter)) # 输出:3
print(next(counter)) # 输出:5

2. cycle(iterable)

cycle 会无限循环迭代一个可迭代对象。

1
2
3
4
5
import itertools

cycler = itertools.cycle(['A', 'B', 'C'])
for _ in range(6):
print(next(cycler)) # 输出:A B C A B C

3. repeat(object, times=None)

repeat 会重复输出相同的对象 times 次,times 可以省略,默认为无限循环。

1
2
3
4
5
import itertools

repeater = itertools.repeat('Hello', 3)
for item in repeater:
print(item) # 输出:Hello Hello Hello

4. combinations(iterable, r)

combinations 生成指定长度 r 的组合,不会重复且不考虑顺序。

1
2
3
4
5
6
import itertools

items = ['A', 'B', 'C']
combs = itertools.combinations(items, 2)
for comb in combs:
print(comb) # 输出:(A, B), (A, C), (B, C)

5. permutations(iterable, r=None)

permutations 生成指定长度 r 的排列。

1
2
3
4
5
6
import itertools

items = ['A', 'B', 'C']
perms = itertools.permutations(items, 2)
for perm in perms:
print(perm) # 输出:(A, B), (A, C), (B, A), (B, C), (C, A), (C, B)

6. chain(*iterables)

chain 将多个可迭代对象连接成一个迭代器。

1
2
3
4
5
6
7
8
import itertools

iterable1 = [1, 2, 3]
iterable2 = ['A', 'B', 'C']
chained = itertools.chain(iterable1, iterable2)

for item in chained:
print(item) # 输出:1 2 3 A B C

二、functools 模块

functools 模块提供了高阶函数和操作可调用对象的工具。

1. reduce(function, iterable[,initializer])

reduce 函数接收一个二元函数和一个可迭代对象,对其元素进行累积运算。

1
2
3
4
5
from functools import reduce

numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, numbers)
print(result) # 输出:10

2. partial(func, *args, **kwargs)

partial 函数用来固定一个函数的某些参数。

1
2
3
4
5
6
7
from functools import partial

def power(base, exp):
return base ** exp

square = partial(power, exp=2)
print(square(5)) # 输出:25

3. lru_cache(maxsize=None)

lru_cache 可以缓存函数的返回结果,优化性能。

1
2
3
4
5
6
7
8
9
from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(10)) # 输出:55

4. wraps(wrapper)

在创建装饰器时,wraps 可以帮助你保持原函数的元数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from functools import wraps

def my_decorator(func):
@wraps(func)
def wrapped(*args, **kwargs):
print("Function called.")
return func(*args, **kwargs)
return wrapped

@my_decorator
def say_hello():
print("Hello!")

say_hello() # 输出:Function called. Hello!
print(say_hello.__name__) # 输出:say_hello

总结

通过以上内容,我们深入探讨了 itertoolsfunctools 模块的常用功能。这些工具不仅能帮助你简化代码,还能提高程序的性能和可读性。希望这些示例能够帮助你在实际项目中更好地应用这些模块!