当前位置: 首页 > news >正文

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 + 1def multiply(x):return x * 2result = 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 selfdef __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 = funcdef __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 ifor value in my_generator():print(value)
0
1
2
  1. 异步生成器 异步生成值。
import asyncio
import nest_asyncionest_asyncio.apply()async def my_gen():for i in range(3):yield iawait 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: strage: intp = Person(name='Alice', age=30)
print(p)
Person(name='Alice', age=30)
  1. NamedTuple 创建不可变的命名元组。
from collections import namedtuplePoint = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p)
Point(x=1, y=2)
  1. 单例模式 确保类只有一个实例。
class Singleton:_instance = Nonedef __new__(cls, *args, **kwargs):if not cls._instance:cls._instance = super().__new__(cls, *args, **kwargs)return cls._instances1 = 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@propertydef value(self):return self._value@value.setterdef value(self, new_value):self._value = new_valueobj = MyClass(10)
print(obj.value)
obj.value = 20
print(obj.value)
10
20
  1. 自定义迭代器 创建自定义的可迭代对象。
class MyIterator:def __init__(self, data):self.data = dataself.index = 0def __iter__(self):return selfdef __next__(self):if self.index < len(self.data):result = self.data[self.index]self.index += 1return resultelse:raise StopIterationmy_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")yieldprint("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 nreturn 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 threadingdef 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 Processdef 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 Queueq = 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 selfdef __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}

相关文章:

python 高级技巧 0706

python 33个高级用法技巧 列表推导式 简化了基于现有列表创建新列表的过程。 squares [x**2 for x in range(10)] print(squares)[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]字典推导式 用简洁的方式创建字典。 square_dict {x: x**2 for x in range(10)} print(square_dict){0…...

面试经典 106. 从中序与后序遍历序列构造二叉树

最近小胖开始找工作了&#xff0c;又来刷苦逼的算法了 555 废话不多说&#xff0c;看这一题&#xff0c;上链接&#xff1a;https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/?envTypestudy-plan-v2&envIdtop-inte…...

如何解决群晖Docker注册表查询失败/无法拉取镜像等问题

文章目录 📖 介绍 📖🏡 演示环境 🏡📒 问题概述 📒📒 解决方案 📒🔖 方法一🔖 方法二🔖 方法三⚓️ 相关链接 🚓️📖 介绍 📖 在群晖(Synology)NAS设备上使用Docker时,我们可能会遇到查询Docker注册表失败,无法拉取Docker镜像的问题。这种情况…...

【Scrapy】 深入了解 Scrapy 中间件中的 process_spider_input 方法

准我快乐地重饰演某段美丽故事主人 饰演你旧年共寻梦的恋人 再去做没流着情泪的伊人 假装再有从前演过的戏份 重饰演某段美丽故事主人 饰演你旧年共寻梦的恋人 你纵是未明白仍夜深一人 穿起你那无言毛衣当跟你接近 &#x1f3b5; 陈慧娴《傻女》 Scrapy 是…...

数据库MySQL---基础篇

存储和管理数据的仓库 MySQL概述 数据库相关概念 数据库&#xff08;DataBase&#xff09;---数据存储的仓库&#xff0c;数据是有组织的进行存储 数据库管理系统&#xff08;DBMS&#xff09;-----操纵和管理数据库的大型软件 SQL----操作关系型数据库的编程语言&#xff…...

欧姆龙安全PLC及周边产品要点指南

电气安全、自动化设备作业安全&#xff0c;向来是非常非常之重要的&#xff01;越来越多的客户在规划新产线、改造既有产线的过程中&#xff0c;明确要求设计方和施工方将安全考虑进整体方案中进行考虑和报价&#xff01;作为一名自动化电气工程师&#xff0c;尤其是高级工程师…...

tableau气泡图与词云图绘制 - 8

气泡图及词云图绘制 1. 气泡图绘制1.1 选择相关属性字段1.2 选择气泡图1.3 设置颜色1.4 设置标签1.5 设置单位 2. 气泡图绘制 - 22.1 类别筛选2.2 页面年份获取2.3 行列获取2.4 历史轨迹显示 3. 词云图绘制3.1 筛选器3.2 选择相关属性3.3 选择气泡图3.4 设置类型颜色3.5 设置形…...

C语言 找出一个二维数组中的鞍点

找出一个二维数组中的鞍点,即该位置上的元素在该行上最大、在该列上最小。也可能没有鞍点。 #include <stdio.h>int main() {int matrix[4][4] {{10, 17, 13, 28},{21, 14, 16, 40},{30, 42, 23, 39},{24, 11, 19, 17}};int n 4, m 4;int found 0;for (int i 0; i …...

【笔记】在linux中设置错文件如何重置

以mysql的auto.cnf文件为例...

DNS中的CNAME与A记录:为什么无法共存A解析和C解析?

在互联网的世界中&#xff0c;DNS&#xff08;域名系统&#xff09;扮演着至关重要的角色&#xff0c;它将易于记忆的域名转换为计算机可识别的IP地址。在这个过程中&#xff0c;两种常见的DNS记录类型——CNAME记录和A记录——经常被提及。然而&#xff0c;它们之间存在着一些…...

线程和进程

文章目录 进程和线程进程线程案例 时间片概念调度方式线程的创建和启动第一种创建方式第二种创建方式&#xff08;匿名内部类&#xff09;第三种创建方式&#xff08;Runnable接口&#xff09;main线程和t线程之间的关系 线程的名字线程的优先级线程状态 进程和线程 进程 在计…...

【JavaEE】 简单认识CPU

&#x1f435;本篇文章将对cpu的相关知识进行讲解 一、认识CPU 下图是简略的冯诺依曼体系结构图 上图中&#xff0c;存储器用来存储数据&#xff0c;注意在存储器中都是以二进制的形式存储数据的&#xff0c;CPU就是中央处理器&#xff0c;其功能主要是进行各种算术运算和各种…...

《数字图像处理-OpenCV/Python》第17章:图像的特征描述

《数字图像处理-OpenCV/Python》第17章&#xff1a;图像的特征描述 本书京东 优惠购书链接 https://item.jd.com/14098452.html 本书CSDN 独家连载专栏 https://blog.csdn.net/youcans/category_12418787.html 第17章&#xff1a;图像的特征描述 特征检测与匹配是计算机视觉的…...

考研数学什么时候开始强化?如何保证进度不掉队?

晚了。我是实在人&#xff0c;不给你胡乱吹&#xff0c;虽然晚了&#xff0c;但相信我&#xff0c;还有的救。 实话实说&#xff0c;从七月中旬考研数一复习完真的有点悬&#xff0c;需要超级高效快速... 数二的时间也有点紧张... 中间基本没有试错的时间&#xff0c;让你换…...

Node.js的下载、安装和配置

天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物。 每个人都有惰性&#xff0c;但不断学习是好好生活的根本&#xff0c;共勉&#xff01; 文章均为学习整理笔记&#xff0c;分享记录为主&#xff0c;如有错误请指正&#xff0c;共同学习进步。…...

java.util.Properties类介绍

java.util.Properties 是 Java 编程语言中的一个类,用于管理应用程序的配置信息,它继承自 java.util.Hashtable 类,因此它也是基于键值对的数据结构。主要用途是存储应用程序的配置参数,比如数据库连接信息、用户设置等。 以下是 Properties 类的一些主要特点和用法: 存储…...

SpringBoot后端验证码-防止密码爆破功能

一、简介 为了防止网站的用户被通过密码典爆破。引入验证码的功能是十分有必要的。而前端的验证码又仅仅是只防君子不防小人。通过burpsuit等工具很容易就会被绕过。所以后端实现的验证码才是对用户信息安全的一大重要保障。 实现思路&#xff1a; 1.引入图形生成的依赖 2.生成…...

ChatEval:通过多代理辩论提升LLM文本评估质量

论文地址:ChatEval: Towards Better LLM-based Evaluators through Multi-Agent Debate | OpenReviewText evaluation has historically posed significant challenges, often demanding substantial labor and time cost. With the emergence of large language models (LLMs…...

关于美国服务器IP的几个常见问题

在租用美国服务器时&#xff0c;与之密切相关的一个要素就是IP&#xff0c;关于IP的问题总是有人问起&#xff0c;这里列举几项常见的问题&#xff0c;以供参考。 一、IP收费吗&#xff1f; 一般情况下&#xff0c;在租用服务器时&#xff0c;会赠送几个IP&#xff0c;因为这些…...

redis运维:sentinel模式如何查看所有从节点

1. 连接到sentinel redis-cli -h sentinel_host -p sentinel_port如&#xff1a; redis-cli -h {域名} -p 200182. 发现Redis主服务器 连接到哨兵后&#xff0c;我们可以使用SENTINEL get-master-addr-by-name命令来获取当前的Redis主服务器的地址。 SENTINEL get-master-a…...

React第五十七节 Router中RouterProvider使用详解及注意事项

前言 在 React Router v6.4 中&#xff0c;RouterProvider 是一个核心组件&#xff0c;用于提供基于数据路由&#xff08;data routers&#xff09;的新型路由方案。 它替代了传统的 <BrowserRouter>&#xff0c;支持更强大的数据加载和操作功能&#xff08;如 loader 和…...

UDP(Echoserver)

网络命令 Ping 命令 检测网络是否连通 使用方法: ping -c 次数 网址ping -c 3 www.baidu.comnetstat 命令 netstat 是一个用来查看网络状态的重要工具. 语法&#xff1a;netstat [选项] 功能&#xff1a;查看网络状态 常用选项&#xff1a; n 拒绝显示别名&#…...

Leetcode 3577. Count the Number of Computer Unlocking Permutations

Leetcode 3577. Count the Number of Computer Unlocking Permutations 1. 解题思路2. 代码实现 题目链接&#xff1a;3577. Count the Number of Computer Unlocking Permutations 1. 解题思路 这一题其实就是一个脑筋急转弯&#xff0c;要想要能够将所有的电脑解锁&#x…...

CRMEB 框架中 PHP 上传扩展开发:涵盖本地上传及阿里云 OSS、腾讯云 COS、七牛云

目前已有本地上传、阿里云OSS上传、腾讯云COS上传、七牛云上传扩展 扩展入口文件 文件目录 crmeb\services\upload\Upload.php namespace crmeb\services\upload;use crmeb\basic\BaseManager; use think\facade\Config;/*** Class Upload* package crmeb\services\upload* …...

【HarmonyOS 5 开发速记】如何获取用户信息(头像/昵称/手机号)

1.获取 authorizationCode&#xff1a; 2.利用 authorizationCode 获取 accessToken&#xff1a;文档中心 3.获取手机&#xff1a;文档中心 4.获取昵称头像&#xff1a;文档中心 首先创建 request 若要获取手机号&#xff0c;scope必填 phone&#xff0c;permissions 必填 …...

网站指纹识别

网站指纹识别 网站的最基本组成&#xff1a;服务器&#xff08;操作系统&#xff09;、中间件&#xff08;web容器&#xff09;、脚本语言、数据厍 为什么要了解这些&#xff1f;举个例子&#xff1a;发现了一个文件读取漏洞&#xff0c;我们需要读/etc/passwd&#xff0c;如…...

vue3 daterange正则踩坑

<el-form-item label"空置时间" prop"vacantTime"> <el-date-picker v-model"form.vacantTime" type"daterange" start-placeholder"开始日期" end-placeholder"结束日期" clearable :editable"fal…...

实战设计模式之模板方法模式

概述 模板方法模式定义了一个操作中的算法骨架&#xff0c;并将某些步骤延迟到子类中实现。模板方法使得子类可以在不改变算法结构的前提下&#xff0c;重新定义算法中的某些步骤。简单来说&#xff0c;就是在一个方法中定义了要执行的步骤顺序或算法框架&#xff0c;但允许子类…...

UE5 音效系统

一.音效管理 音乐一般都是WAV,创建一个背景音乐类SoudClass,一个音效类SoundClass。所有的音乐都分为这两个类。再创建一个总音乐类&#xff0c;将上述两个作为它的子类。 接着我们创建一个音乐混合类SoundMix&#xff0c;将上述三个类翻入其中&#xff0c;通过它管理每个音乐…...

EEG-fNIRS联合成像在跨频率耦合研究中的创新应用

摘要 神经影像技术对医学科学产生了深远的影响&#xff0c;推动了许多神经系统疾病研究的进展并改善了其诊断方法。在此背景下&#xff0c;基于神经血管耦合现象的多模态神经影像方法&#xff0c;通过融合各自优势来提供有关大脑皮层神经活动的互补信息。在这里&#xff0c;本研…...