Python_Note

Rudy 2025-5-16 25 5/16

一、推导式写法

1.列表推导式

name = ['Bob', 'Tom', 'Alice']

# 列表推导式:筛选长度>3的名字,并转为大写
result = [name.upper() for name in name if len(name) > 3]

print(result)  # 输出: ['ALICE']

2.字典推导式

# 列表:存放名字
name = ['Bob', 'Tom', 'Alice']

# 字典推导式:key = 名字,value = 名字长度
result = {key: len(key) for key in name}

# {'Bob': 3, 'Tom': 3, 'Alice': 5}
print(result)

3.集合推导式

# 集合推导式:计算 1、2、3 的平方,生成集合 {1, 4, 9}
print({i**2 for i in (1, 2, 3)})

4.列表推导式

# 生成器表达式 (小括号包裹)
a = (x for x in range(1, 10))

# 打印:返回的是 生成器对象,不是直接的数据
print(a)  # <generator object <genexpr> at 0x...>

# 把生成器转换成元组,取出所有值
print(tuple(a))  # (1, 2, 3, 4, 5, 6, 7, 8, 9)

5.迭代器与生成器

# 迭代器基础用法
my_list = [1, 2, 3, 4]  # 不要用 list 做变量名,会覆盖内置函数
it = iter(my_list)       # 创建迭代器对象

# 循环遍历迭代器
for x in it:
# 1 2 3 4 
    print(x, end=" ")
# 生成器
def countdown(n):
    # 生成器函数:倒计时,从 n 递减到 1
    while n > 0:
        yield n
        n -= 1

# 创建生成器对象
generator = countdown(5)

# 通过 next() 手动获取值
print(next(generator))  # 输出: 5
print(next(generator))  # 输出: 4
print(next(generator))  # 输出: 3

# 使用 for 循环迭代剩余的值
for value in generator:
    print(value)        # 输出: 2 1

6.lambda 函数

# 1. map + lambda:对列表每个元素求平方
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # 输出: [1, 4, 9, 16, 25]

# 2. filter + lambda:筛选列表中的偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 输出: [2, 4, 6, 8]

# 3. reduce + lambda:计算列表元素的累积乘积
from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 输出: 120

二、装饰器

# 装饰器语法:使用 @decorator_name 应用在函数或方法上
# Python 内置装饰器:@staticmethod、@classmethod、@property

# 装饰器应用场景:
# 1. 日志记录:记录函数调用信息、参数和返回值
# 2. 性能分析:测量函数执行时间
# 3. 权限控制:限制函数访问权限
# 4. 缓存:缓存函数结果提升性能

# 内置装饰器说明:
# @staticmethod:定义静态方法,无需实例化类即可调用
# @classmethod:定义类方法,第一个参数为类本身(cls)
# @property:将方法转为属性,可直接访问/赋值

class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method.")

    @classmethod
    def class_method(cls):
        print(f"This is a class method of {cls.__name__}.")

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

# 使用示例
MyClass.static_method()
MyClass.class_method()

obj = MyClass()
obj.name = "Alice"
print(obj.name)

1.__name__ 属性

内置的函数 dir() 可以找到模块内定义的所有名称。以一个字符串列表的形式返回:

2.类和对象

# 定义类
class MyClass:
    """类的说明文档"""
    i = 12345           # 类属性

    def f(self):        # 实例方法(必须带 self)
        return 'hello world'

# 实例化
x = MyClass()

# 调用属性和方法
print(x.i)
print(x.f())

2. 构造方法 init

class MyClass:
    # 构造方法:创建对象时自动执行
    def __init__(self):
        self.data = []  # 实例属性

# 带参数的构造方法(最常用)
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

stu = Student("小明", 18)
print(stu.name, stu.age)

3.私有变量(无法外部直接访问)

class Test:
    def __init__(self):
        self.__secretCount = 0  # 双下划线 = 私有变量

obj = Test()
# print(obj.__secretCount)  # 报错!外部不能访问私有变量

4. 常用内置属性

class MyClass:
    """这是一个测试类"""
    pass

print(MyClass.__name__)   # 输出类名:MyClass
print(dir(MyClass))       # 列出所有属性和方法(列表形式)

三、多线程、多协程、多进程

方式 核心原理 适合任务 速度 资源占用
多进程 Process 独立内存,真正并行 CPU 密集型(计算) 最大
多线程 Thread 共享内存,受 GIL 限制 I/O 密集型(等待)
协程 Coroutine 单线程内切换,用户态调度 大量 I/O(爬虫 / 请求) 极快 极小

1.多线程处理

'''多线程-线程池'''
from time import sleep, time
from concurrent import futures

start_time = time()

def download_img(url):

    print(f'{url} downloading...')
    sleep(1)


with futures.ThreadPoolExecutor() as executor:
    result = executor.map(download_img, range(10))
    for result in result:
        print(result)

end_time = time()
# Elapsed time: 1.01s
print(f'Elapsed time: {end_time - start_time:.2f}s')
"""

2.协程

import asyncio
import time

start = time.time()


async def task(name):
    print(f"协程 {name} 开始")
    await asyncio.sleep(1)
    print(f"协程 {name} 结束")


async def main():
    await asyncio.gather(task(1), task(2), task(3), task(4))


asyncio.run(main())
# 总耗时:1
print("协程总耗时:", time.time() - start)

3.多进程

'''进程池'''
from time import time, sleep
from concurrent.futures import ProcessPoolExecutor


def calculate(n):
    sleep(1)
    return f"calculate complete of {n}"


if __name__ == '__main__':
    start = time()
    with ProcessPoolExecutor() as executor:
        result = executor.map(calculate, range(10))

    end = time()
    # Elapsed time: 2.00s
    print(f"take time: {end - start:.2f}s")

 

 

 

- THE END -
最后修改:2026年3月25日
0

非特殊说明,本博所有文章均为博主原创。

共有 0 条评论