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}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/777458.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Java——继承(Inheritance)

一、继承简要介绍 1、继承是什么 在Java中&#xff0c;继承是一种面向对象编程的重要特性&#xff0c;它允许一个类&#xff08;子类或派生类&#xff09;继承另一个类&#xff08;父类或基类&#xff09;的属性和方法。继承的目的是实现代码的重用和设计的层次化。 子类通常…

探索LlamaIndex:如何用Django打造高效知识库检索

简介 LlamaIndex&#xff08;前身为 GPT Index&#xff09;是一个数据框架&#xff0c;为了帮助我们去建基于大型语言模型&#xff08;LLM&#xff09;的应用程序。 主要用于处理、构建和查询自定义知识库。 它支持多种数据源格式 excel&#xff0c;txt&#xff0c;pdf&…

DaViT(ECCV 2022,Microsoft)

paper&#xff1a;DaViT: Dual Attention Vision Transformers official implementation&#xff1a;https://github.com/dingmyu/davit third-party implementation&#xff1a;https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/davit.py 出发点…

独家揭秘!格行随身WiFi‘骄傲’宣言背后的震撼行业的真相!随身WiFi行业内黑马

近几年以来&#xff0c;随行WiFi产品呈现爆发式增长&#xff0c;随行WiFi的火爆&#xff0c;是技术进步带给消费者的一种“福利”&#xff0c;各大直播间也充斥着品牌各异的随身WiFi。但真正脱颖而出、赢得消费者信赖的优质品牌却凤毛麟角。而其中最受欢迎的格行随身WiFi也因设…

Java语言+后端+前端Vue,ElementUI 数字化产科管理平台 产科电子病历系统源码

Java语言后端前端Vue,ElementUI 数字化产科管理平台 产科电子病历系统源码 Java开发的数字化产科管理系统&#xff0c;已在多家医院实施&#xff0c;支持直接部署。系统涵盖孕产全程&#xff0c;包括门诊、住院、统计和移动服务&#xff0c;整合高危管理、智能提醒、档案追踪等…

Stream练习

运用点&#xff1a; 流内数据类型转换(map)、filter、limit、skip、concat(让两个流合并) 题目&#xff1a; 操作1、2&#xff1a; ArrayList<String> manList new ArrayList<>();ArrayList<String> womanList new ArrayList<>();Collections.addAl…

C++之static关键字

文章目录 前提正文多重定义extern关键字使用staticstatic 全局变量(在.cpp文件中定义)static变量存放在哪里static变量可不可以放在.h文件中 static 函数static局部变量static 成员变量static 成员函数 总结参考链接 前提 好吧&#xff0c;八股&#xff0c;我又回来了。这次想…

8.14 矢量图层面要素2.5D渲染

文章目录 前言2.5D渲染QGis设置面符号为2.5D二次开发代码实现2.5D 总结 前言 本章介绍矢量图层面要素2.5D渲染的使用说明&#xff1a;文章中的示例代码均来自开源项目qgis_cpp_api_apps 2.5D渲染 2.5D渲染可以将多边形渲染为类3D效果。 QGis设置面符号为2.5D 以"hou…

数据库7.4

第二次作业 1.登陆数据库 2.创建数据库zoo 3.修改数据库zoo字符集为gbk 4.选择当前数据库为zoo 5.查看创建数据库zoo信息 6.删除数据库zoo C:\Windows\System32>mysql -uroot -p20040830Nmx mysql> create database zoo; alter database zoo character set gbk; mys…

Java springboot校园管理系统源码

Java springboot校园管理系统源码-014 下载地址&#xff1a;https://download.csdn.net/download/xiaohua1992/89364089 技术栈 运行环境&#xff1a;jdk8 tomcat9 mysql5.7 windows10 服务端技术&#xff1a;Spring Boot Mybatis VUE 使用说明 1.使用Navicati或者其它工…

VBA初学:零件成本统计之三(获取材料外协的金额)

第三步&#xff0c;从K3的数据库中获取金额 我这里是使用循环&#xff0c;通过任务单号将金额汇总出来&#xff0c;如果使用数组的话&#xff0c;还要按任务单写GROUP&#xff0c;还要去对应&#xff0c;不如循环直接一点 获取材料和外协金额的表格Sub getje()Dim rowcount A…

【JAVA入门】Day13 - 代码块

【JAVA入门】Day13 - 代码块 文章目录 【JAVA入门】Day13 - 代码块一、局部代码块二、构造代码块三、静态代码块 在 Java 中&#xff0c;两个大括号 { } 中间的部分叫一个代码块&#xff0c;代码块又分为&#xff1a;局部代码块、构造代码块、静态代码块三种。 一、局部代码块…

Linux应用---信号

写在前面&#xff1a;在前面的学习过程中&#xff0c;我们学习了进程间通信的管道以及内存映射的方式。这次我们介绍另外一种应用较为广泛的进程间通信的方式——信号。信号的内容比较多&#xff0c;是学习的重点&#xff0c;大家一定要认真学&#xff0c;多多思考。 一、信号概…

ASP.NET Core----基础学习01----HelloWorld---创建Blank空项目

文章目录 1. 创建新项目--方式一&#xff1a; blank2. 程序各文件介绍&#xff08;Project name &#xff1a;ASP.Net_Blank&#xff09;&#xff08;1&#xff09;launchSettings.json 启动方式的配置文件&#xff08;2&#xff09;appsettings.json 基础配置file参数的读取&a…

Vue 前端修改页面标题无需重新打包即可生效

在public文件夹下创建config.js文件 index.html页面修改 其他页面的标题都可以用window.title来引用就可以了&#xff01;

【算法】(C语言):冒泡排序、选择排序、插入排序

冒泡排序 从第一个数据开始到第n-1个数据&#xff0c;依次和后面一个数据两两比较&#xff0c;数值小的在前。最终&#xff0c;最后一个数据&#xff08;第n个数据&#xff09;为最大值。从第一个数据开始到第n-2个数据&#xff0c;依次和后面一个数据两两比较&#xff0c;数值…

商务办公优选!AOC Q27E3S2商用显示器,打造卓越新体验!

摘要&#xff1a;助办公室一族纵横职场&#xff0c;实现高效舒适办公&#xff01; 在日常商务办公中&#xff0c;对于办公室一族来说总有太多“难难难难难点”&#xff1a;工作任务繁琐&#xff0c;熬夜加班心力交瘁、长时间伏案工作导致颈椎、眼睛等出现问题&#xff0c;职业…

【吊打面试官系列-MyBatis面试题】为什么说 Mybatis 是半自动 ORM 映射工具?它与全自动的区别在哪里?

大家好&#xff0c;我是锋哥。今天分享关于 【为什么说 Mybatis 是半自动 ORM 映射工具&#xff1f;它与全自动的区别在哪里&#xff1f;】面试题&#xff0c;希望对大家有帮助&#xff1b; 为什么说 Mybatis 是半自动 ORM 映射工具&#xff1f;它与全自动的区别在哪里&#xf…

[从0开始轨迹预测][NMS]:NMS的应用(目标检测、轨迹预测)

非极大值抑制&#xff08;Non-Maximum Suppression&#xff0c;简称NMS&#xff09;是一种在计算机视觉中广泛应用的算法&#xff0c;主要用于消除冗余和重叠的边界框。在目标检测任务中&#xff0c;尤其是在使用诸如R-CNN系列的算法时&#xff0c;会产生大量的候选区域&#x…

Redis基础教程(九):redis有序集合

&#x1f49d;&#x1f49d;&#x1f49d;首先&#xff0c;欢迎各位来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里不仅可以有所收获&#xff0c;同时也能感受到一份轻松欢乐的氛围&#xff0c;祝你生活愉快&#xff01; &#x1f49d;&#x1f49…