python 高级技巧 0706

python 33个高级用法技巧

  1. 列表推导式 简化了基于现有列表创建新列表的过程。
squares = [x**2 for x in range(10)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  1. 字典推导式 用简洁的方式创建字典。
square_dict = {x: x**2 for x in range(10)}
print(square_dict)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
  1. 集合推导式 生成没有重复值的集合。
unique_squares = {x**2 for x in range(10)}
print(unique_squares)
{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
  1. 生成器表达式 创建一个按需生成值的迭代器。
gen = (x**2 for x in range(10))
print(list(gen))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  1. Lambda 函数 创建小型匿名函数。
add = lambda x, y: x + y
print(add(3, 5))
8
  1. Map 函数 将一个函数应用到输入列表的所有项目上。
squares = list(map(lambda x: x**2, range(10)))
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  1. Filter 函数 从序列中过滤出满足条件的项目。
even_numbers = list(filter(lambda x: x % 2 == 0, range(10)))
print(even_numbers)
[0, 2, 4, 6, 8]
  1. Reduce 函数 对序列中的所有元素应用累积函数。
from functools import reduce
sum_all = reduce(lambda x, y: x + y, range(10))
print(sum_all)
45
  1. 链式比较 允许在一行中进行多个比较。
x = 5
result = 1 < x < 10
print(result)
True
  1. 枚举 生成枚举对象,提供索引和值。
list1 = ['a', 'b', 'c']
for index, value in enumerate(list1):
    print(index, value)

0 a
1 b
2 c
  1. 解包 从容器中提取多个值。
a, b, c = [1, 2, 3]
print(a, b, c)
print(*[1, 2, 3])
1 2 3
1 2 3
  1. 链式函数调用 链式调用多个函数。
def add(x):
    return x + 1

def multiply(x):
    return x * 2

result = multiply(add(3))
print(result)
8
  1. 上下文管理器 自动处理资源管理。
with open('file.txt', 'w') as f:
    f.write('Hello, World!')
  1. 自定义上下文管理器 创建自定义资源管理逻辑。
class MyContext:
    def __enter__(self):
        print('Entering')
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print('Exiting')

with MyContext() as m:
    print('Inside')
Entering
Inside
Exiting
  1. 装饰器 修改函数的行为。
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.
  1. 类装饰器 使用类来实现装饰器。
class Decorator:
    def __init__(self, func):
        self.func = func

    def __call__(self):
        print("Something is happening before the function is called.")
        self.func()
        print("Something is happening after the function is called.")

@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.
  1. 生成器函数 创建迭代器,逐个返回值。
def my_generator():
    for i in range(3):
        yield i

for value in my_generator():
    print(value)
0
1
2
  1. 异步生成器 异步生成值。
import asyncio
import nest_asyncio

nest_asyncio.apply()

async def my_gen():
    for i in range(3):
        yield i
        await asyncio.sleep(1)

async def main():
    async for value in my_gen():
        print(value)

asyncio.run(main())
0
1
2
  1. 元类 控制类的创建行为。
class Meta(type):
    def __new__(cls, name, bases, dct):
        print(f'Creating class {name}')
        return super().__new__(cls, name, bases, dct)

class MyClass(metaclass=Meta):
    pass
Creating class MyClass
  1. 数据类 简化类的定义。
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

p = Person(name='Alice', age=30)
print(p)
Person(name='Alice', age=30)
  1. NamedTuple 创建不可变的命名元组。
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p)
Point(x=1, y=2)
  1. 单例模式 确保类只有一个实例。
class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance

s1 = Singleton()
s2 = Singleton()
print(s1 is s2)
True
  1. 多继承 使用多个基类创建类。
class Base1:
    def __init__(self):
        print("Base1")

class Base2:
    def __init__(self):
        print("Base2")

class Derived(Base1, Base2):
    def __init__(self):
        super().__init__()
        Base2.__init__(self)

d = Derived()

Base1
Base2
  1. 属性 控制属性的访问和修改。
class MyClass:
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, new_value):
        self._value = new_value

obj = MyClass(10)
print(obj.value)
obj.value = 20
print(obj.value)
10
20
  1. 自定义迭代器 创建自定义的可迭代对象。
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):
            result = self.data[self.index]
            self.index += 1
            return result
        else:
            raise StopIteration

my_iter = MyIterator([1, 2, 3])
for value in my_iter:
    print(value)
1
2
3
  1. 上下文管理器 使用 contextlib简化上下文管理。
from contextlib import contextmanager

@contextmanager
def my_context():
    print("Entering")
    yield
    print("Exiting")

with my_context():
    print("Inside")

Entering
Inside
Exiting
  1. 函数缓存 缓存函数结果以提高性能。
from functools import lru_cache

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

print([fib(n) for n in range(10)])

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
  1. 多线程 使用线程并发执行任务。
import threading

def print_numbers():
    for i in range(5):
        print(i)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
0
1
2
3
4
  1. 多进程 使用进程并发执行任务。
from multiprocessing import Process

def print_numbers():
    for i in range(5):
        print(i)

process = Process(target=print_numbers)
process.start()
process.join()
0
1
2
3
4
  1. 队列 使用队列在线程或进程间传递数据。
from queue import Queue

q = Queue()
for i in range(5):
    q.put(i)

while not q.empty():
    print(q.get())

0
1
2
3
4
  1. 信号量 控制对资源的访问。
import threading

# 创建一个信号量对象,初始值为2
semaphore = threading.Semaphore(2)

# 定义一个访问资源的函数


def access_resource():
    # 使用上下文管理器来获取信号量
    with semaphore:
        # 模拟资源访问的操作
        print("Resource accessed")


# 创建4个线程,每个线程都运行access_resource函数
threads = [threading.Thread(target=access_resource) for _ in range(4)]

# 启动所有线程
for thread in threads:
    thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()
Resource accessed
Resource accessed
Resource accessed
Resource accessed
  1. 上下文管理器协议 创建自定义资源管理逻辑。
class MyContext:
    def __enter__(self):
        print('Entering')
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print('Exiting')

with MyContext() as m:
    print('Inside')

Entering
Inside
Exiting
  1. 序列化、反序列化
import pickle

# 创建一个数据字典
data = {'a': 1, 'b': 2, 'c': 3}

# 将数据序列化并写入文件
with open('data.pkl', 'wb') as f:
    pickle.dump(data, f)
import pickle

# 从文件中读取序列化的数据
with open('data.pkl', 'rb') as f:
    loaded_data = pickle.load(f)

# 打印反序列化后的数据
print(loaded_data)
{'a': 1, 'b': 2, 'c': 3}

相关推荐

  1. python 高级技巧 0706

    2024-07-09 22:16:04       21 阅读
  2. Python学习入门(3)—— 高级技巧

    2024-07-09 22:16:04       42 阅读
  3. 深入探讨Python高级技术

    2024-07-09 22:16:04       23 阅读
  4. python-0006-django路由

    2024-07-09 22:16:04       47 阅读
  5. Python语言例题集(006

    2024-07-09 22:16:04       50 阅读
  6. python 66 个冷知识 0716

    2024-07-09 22:16:04       23 阅读
  7. NGINX高级技巧

    2024-07-09 22:16:04       61 阅读
  8. GitHub高级搜索技巧

    2024-07-09 22:16:04       54 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 22:16:04       103 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 22:16:04       110 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 22:16:04       92 阅读
  4. Python语言-面向对象

    2024-07-09 22:16:04       99 阅读

热门阅读

  1. 前端面试基础html/js/css

    2024-07-09 22:16:04       22 阅读
  2. crontab定时任务不执行原因排查

    2024-07-09 22:16:04       25 阅读
  3. RTOS系统 -- ARM Cortex-M4 RPMSG之通道初始化函数

    2024-07-09 22:16:04       22 阅读
  4. shell中不常见的命令

    2024-07-09 22:16:04       29 阅读
  5. 直播APP开发源码搭建

    2024-07-09 22:16:04       25 阅读
  6. 自己写个简单的vite插件

    2024-07-09 22:16:04       29 阅读
  7. ROS melodic版本卸载---Ubuntu18.04

    2024-07-09 22:16:04       25 阅读
  8. Ubuntu手动编译源码安装Python

    2024-07-09 22:16:04       25 阅读
  9. [C++][CMake][生成可执行文件][下]详细讲解

    2024-07-09 22:16:04       32 阅读
  10. ubuntu防火墙指定端口开放设置

    2024-07-09 22:16:04       27 阅读
  11. ubuntu20.04安装ros1

    2024-07-09 22:16:04       26 阅读