Python_Module
发表于|更新于|Python
|浏览量:
Python Module
文章作者: xhj
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 xhj的博客!
相关推荐
2024-10-02
2_function
函数18. 用数量可变的位置参数减少视觉杂讯首先看第一段代码: 1234567891011def foo(message, values): if not values: print(message) else: print("%s: %s"%(message, ",".join([str(v) for v in values])))foo("my numbers are", [1,2,3])# my numbers are: 1,2,3foo("no numbers.", [])# no numbers. 可以看出,第二次不输入 values 时的调用不是很优雅,而由于之前定义过 foo 函数必须要传 values 这个参数,因此只能按照这样的调用方法。为了避免这样没有意义的空 list 传入,可以使用 * 星号参数来避免掉第二次调用的空 list。修改后的代码如下: 1234567891011def foo(message, *values): if...
2025-07-13
Python中functools库的@cache注解的原理与用法
Python functools 库中的 @cache 装饰器@cache 是 Python 3.9+ 中引入的一个装饰器,用于自动缓存函数的结果,基于函数的参数。它是 @lru_cache(maxsize=None) 的简化版本。 原理@cache 的核心原理是 记忆化(Memoization): 参数作为键:将函数的参数转换为哈希键 结果缓存:将函数返回值存储在与参数键对应的缓存中 命中返回:当相同参数再次出现时,直接返回缓存结果,避免重复计算 基本用法12345678910111213from functools import cache@cachedef fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)# 首次计算会执行实际计算print(fibonacci(10)) # 55# 相同参数再次调用,直接返回缓存结果print(fibonacci(10)) # 55 (从缓存返回) 与 @lru_cache 的比较12345678910fr...
2021-07-21
复盘|天堂硅谷·数字经济算法编程大赛
复盘|天堂硅谷·数字经济算法编程大赛题目-01 化学反应【模拟】按题意模拟(可以用大根堆或者平衡树),每次找两个最大的出来,直到没有剩余或只剩一个。 1 2 3 4 5 6 7 8 9 #平衡树 from sortedcontainers import SortedList class Solution: def lastMaterial(self, material: List[int]) -> int: s = SortedList(material) while len(s) > 1: a, b = s.pop(), s.pop() if a != b: s.add(a - b) return s[0] if s else 0 1 2 3 4 5 6 7 8 9 #大根堆 class Solution: def lastMaterial(self, material: List[int]) -> int: ...
2025-07-16
Python异步编程概念与用法详解
我来详细解释Python异步编程中的核心概念,让你彻底理解async/await的工作原理。 1. 基本概念asyncasync关键字用于定义异步函数(协程函数): 12345async def my_function(): return "Hello"# 调用异步函数会返回一个协程对象,而不是直接执行coroutine = my_function() awaitawait用于挂起当前协程,等待另一个协程完成: 123async def main(): result = await my_function() # 等待my_function完成 print(result) 2. Future对象Future代表一个异步操作的最终结果: 123456789101112131415import asyncioasync def example_future(): # 创建Future对象 future = asyncio.Future() # 设置结果 future.set_result("...
2025-07-06
Python_Metaclass
Python Metaclass参考资料 What are metaclasses in Python?
2025-07-02
PyTorch非阻塞传输参数详解
torch.cuda.Event() 是PyTorch中用于精确测量GPU操作时间和实现细粒度同步的工具。 基本用法创建CUDA Event12345import torch# 创建CUDA事件start_event = torch.cuda.Event(enable_timing=True) # 启用计时功能end_event = torch.cuda.Event(enable_timing=True) record() 方法record() 方法在GPU的当前流中插入一个事件记录点。 基本record用法12345678# 在GPU流中记录事件start_event.record() # 记录开始时间点# 执行一些GPU操作x = torch.randn(1000, 1000, device='cuda')y = x * x + 2 * x + 1end_event.record() # 记录结束时间点 synchronize() 方法synchronize() 方法阻塞CPU执行,直到事件完成。 基本synchronize用法123456# 等...