白骑士的Python教学进阶篇 2.4 高级数据结构

系列目录

上一篇:白骑士的Python教学进阶篇 2.3 文件操作​​​​​​​

        在Python中,掌握高级数据结构可以显著提升你的编程效率和代码可读性。高级数据结构包括列表推导式、生成器与迭代器以及装饰器。本文将详细介绍这些高级数据结构,帮助你在实际编程中更好地运用它们。

列表推导式

        列表推导式(List Comprehensions)是Python的一种简洁的语法,用于生成新的列表。通过列表推导式,可以用一行代码表达复杂的列表生成逻辑,增强代码的可读性和简洁性。

基本语法

        列表推导式的基本语法如下:

[expression for item in iterable if condition]

        'expression':生成新列表中元素的表达式。

        ’item‘:从 ‘iterable’ 中取出的元素。

        'iterable':一个可迭代对象,如列表、元组、字符串等。

        ’condition‘:一个可选的过滤条件,只有满足条件的元素才会包含在新列表中。

示例

        生成平方数列表:

squares = [x ** 2 for x in range(10)]
print(squares)

        输出:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

        过滤偶数并生成其平方:

even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
print(even_squares)

        输出:

[0, 4, 16, 36, 64]

        使用嵌套循环生成二维坐标:

coordinates = [(x, y) for x in range(3) for y in range(3)]
print(coordinates)

        输出:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

生成器与迭代器

        生成器和迭代器是Python中用于高效处理大量数据的强大工具。它们可以在不占用大量内存的情况下生成序列数据。

迭代器

        迭代器是一种对象,它实现了迭代协议,包括 '__iter__()' 和 '__next__()' 方法。迭代器可以用于逐个访问集合的元素,而不需要一次性将所有元素加载到内存中。

示例

class MyIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration

        result = self.data[self.index]
        self.index += 1
        return result

my_iter = MyIterator([1, 2, 3])
for item in my_iter:
    print(item)

        输出:

1
2
3

生成器

        生成器是使用 'yield' 关键字的函数。每次调用生成器的 '__next__()' 方法时,生成器函数会运行到 'yield' 语句并返回结果,然后暂停,下一次调用时从暂停处继续执行。

示例

        简单生成器:

def simple_generator():
    yield 1
    yield 2
    yield 3

gen = simple_generator()

for value in gen:
    print(value)

        输出:

1
2
3

        无限斐波那契序列生成器:

def fibonacci():
    a, b = 0, 1

    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()

for _ in range(10):
    print(next(fib))

        输出:

0
1
1
2
3
5
8
13
21
34

        生成器表达式是生成器的简写形式,类似于列表推导式,但使用小括号而不是方括号。

gen_exp = (x ** 2 for x in range(10))

for value in gen_exp:
    print(value)

装饰器

        装饰器是一种高级函数,它允许你在不修改函数代码的前提下,增强或修改函数的行为。装饰器通常用于日志记录、权限检查、缓存等场景。

基本语法

        装饰器是一个返回函数的高阶函数,通常使用 '@decorator_name' 语法糖来应用装饰器。

示例

        基本装饰器:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

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


say_hello()

        输出:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

        带参数的装饰器:

def repeat(num_times):
    def decorator_repeat(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat

@repeat(num_times=3)
def greet(name):
    print(f"Hello, {name}!")


greet("Alice")

        输出:

Hello, Alice!
Hello, Alice!
Hello, Alice!

        类装饰器:

class CountCalls:
    def __init__(self, func):
        self.func = func
        self.num_calls = 0

    def __call__(self, *args, **kwargs):
        self.num_calls += 1
        print(f"Call {self.num_calls} of {self.func.__name__}")
        return self.func(*args, **kwargs)

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


say_hello()
say_hello()

        输出:
 

Call 1 of say_hello
Hello!
Call 2 of say_hello
Hello!

结论

        高级数据结构如列表推导式、生成器与迭代器以及装饰器,是Python提供的强大工具,使开发者可以编写简洁、高效、可维护的代码。通过掌握这些高级特性,可以在实际项目中更灵活地处理复杂的数据操作,提高代码的执行效率,并且能够在不改变原有代码逻辑的情况下,轻松地扩展和增强功能。这些特性不仅提升了编程技能,也为解决实际问题提供了更多的解决方案。希望在实践中多多应用这些高级数据结构,享受Python编程的乐趣。

下一篇:白骑士的Python教学高级篇 3.1 多线程与多进程​​​​​​​

  • 27
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白骑士所长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值