从入门到高手的99个python案例(2)

2024-06-15 16:04
文章标签 python 入门 案例 99 高手

本文主要是介绍从入门到高手的99个python案例(2),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

51. 列表和数组比较 - 列表通用,NumPy数组高效。

import numpy as np  normal_list = [1, 2, 3]  
np_array = np.array([1, 2, 3])  
print(np_array.shape)  # 输出 (3,), 数组有形状信息  

52. Python的内置模块datetime - 处理日期和时间。

from datetime import datetime  
now = datetime.now()  
print(now.strftime("%Y-%m-%d %H:%M:%S"))  

53. Python的os模块 - 操作文件和目录。

import os  
print(os.getcwd())  # 输出当前工作目录  

54. 列表推导式中的条件和循环 - 结合使用。

evens = [x for x in range(10) if x % 2 == 0 for y in range(5) if y % 2 == 0]  
print(evens)  

55. 迭代器和生成器的使用场景 - 数据处理和节省内存。

# 使用生成器处理大文件  
def read_large_file(file_path, chunk_size=1024):  with open(file_path, "r") as file:  while True:  chunk = file.read(chunk_size)  if not chunk:  break  yield chunk  for line in read_large_file("large.txt"):  process(line)  

56. zip()函数 - 同时遍历多个序列。

names = ["Alice", "Bob", "Charlie"]  
ages = [25, 30, 35]  
pairs = zip(names, ages)  
print(list(pairs))  # 输出 [('Alice', 25), ('Bob', 30), ('Charlie', 35)]  

57. enumerate()函数 - 为列表元素添加索引。

fruits = ["apple", "banana", "cherry"]  
for index, fruit in enumerate(fruits):  print(f"{index}: {fruit}")  

58. itertools模块 - 提供高效迭代工具。

from itertools import product  
result = product("ABC", repeat=2)  
print(list(result))  # 输出 [('A', 'A'), ('A', 'B'), ('A', 'C'), ..., ('C', 'C')]  

59. json模块 - 序列化和反序列化数据。

import json  
data = {"name": "Alice", "age": 25}  
json_data = json.dumps(data)  
print(json_data)  

60. 递归函数 - 用于解决分治问题。

def factorial(n):  if n == 0 or n == 1:  return 1  else:  return n * factorial(n - 1)  print(factorial(5))  # 输出 120  

61. os.path模块 - 文件路径处理。

import os.path  
path = "/home/user/documents"  
print(os.path.exists(path))  # 输出 True 或 False  

62. random模块 - 随机数生成。

import random  
random_number = random.randint(1, 10)  
print(random_number)  

63. re模块 - 正则表达式操作。

import re  
text = "Today is 2023-04-01"  
match = re.search(r"\d{4}-\d{2}-\d{2}", text)  
print(match.group())  # 输出 "2023-04-01"  

64. requests - 发送HTTP请求。

import requests  
response = requests.get("https://api.example.com")  
print(response.status_code)  

65. Pandas - 大数据处理。

import pandas as pd  
df = pd.DataFrame({"Name": ["Alice", "Bob"], "Age": [25, 30]})  
print(df)  

66. matplotlib - 数据可视化。

import matplotlib.pyplot as plt  
plt.plot([1, 2, 3, 4])  
plt.show()  

67. logging模块 - 日志记录。

import logging  
logger = logging.getLogger(__name__)  
logger.info("This is an info message")  

68. asyncio - 异步编程。

import asyncio  
async def slow_task():  await asyncio.sleep(1)  return "Task completed"  loop = asyncio.get_event_loop()  
result = loop.run_until_complete(slow_task())  
print(result)  

69. contextlib模块 - 非阻塞上下文管理。

from contextlib import asynccontextmanager  
@asynccontextmanager  
async def acquire_lock(lock):  async with lock:  yield  async with acquire_lock(lock):  # do something  

70. asyncio.gather - 异步并发执行。

tasks = [asyncio.create_task(task) for task in tasks_to_run]  
results = await asyncio.gather(*tasks)  

71. asyncio.sleep - 异步等待一段时间。

await asyncio.sleep(2)  # 程序在此暂停2秒  

72. asyncio.wait - 等待多个任务完成。

done, pending = await asyncio.wait(tasks, timeout=10)  

73. asyncio.subprocess - 异步执行外部命令。

import asyncio.subprocess as sp  
proc = await sp.create_subprocess_exec("ls", "-l")  
await proc.communicate()  

74. concurrent.futures - 多线程/进程执行。

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor  with ThreadPoolExecutor() as executor:  results = executor.map(function, arguments)  

75. timeit模块 - 测试代码执行速度。

import timeit  
print(timeit.timeit("your_code_here", globals=globals()))  

76. pickle模块 - 序列化和反序列化对象。

import pickle  
serialized = pickle.dumps(obj)  
deserialized = pickle.loads(serialized)  

77. logging.handlers模块 - 多种日志输出方式。

handler = RotatingFileHandler("app.log", maxBytes=1000000)  
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")  
handler.setFormatter(formatter)  
logger.addHandler(handler)  

78. asyncio.Queue - 异步队列。

queue = asyncio.Queue()  
await queue.put(item)  
result = await queue.get()  

79. asyncio.Event - 异步信号量。

event = asyncio.Event()  
event.set()  # 设置信号  
await event.wait()  # 等待信号  

80. asyncio.Lock - 互斥锁,防止并发修改。

async with await asyncio.Lock():  # 获取锁后执行  critical_section()  

81. asyncio.gatherasyncio.wait_for的区别 - 异步任务管理。

  • gather: 并行执行多个任务,等待所有任务完成。

  • wait_for: 等待单个任务完成,其他任务继续运行。

82. asyncio.sleepasyncio.sleep_after - 异步延时和定时任务。

  • sleep: 直接暂停当前协程。

  • sleep_after: 定义一个延迟后执行的任务。

83. aiohttp - HTTP客户端库。

import aiohttp  
async with aiohttp.ClientSession() as session:  async with session.get("https://example.com") as response:  data = await response.text()  

84. asyncio.shield - 防止被取消任务中断。

async def task():  await shield(some_long_running_task())  # 如果外部取消任务,task将继续运行,不会影响内部任务  
asyncio.create_task(task())  

85. asyncio.run - 简化异步程序执行。

asyncio.run(main_coroutine())  

86. asyncio.iscoroutinefunction - 检查是否为协程函数。

if asyncio.iscoroutinefunction(some_function):  await some_function()  

87. asyncio.all_tasks - 获取所有任务。

tasks = asyncio.all_tasks()  
for task in tasks:  task.cancel()  

88. asyncio.wait_forasyncio.timeout - 设置超时限制。

try:  result = await asyncio.wait_for(some_task, timeout=5.0)  
except asyncio.TimeoutError:  print("Task timed out")  

89. asyncio.sleep_timeout - 异步睡眠并设置超时。

await asyncio.sleep_timeout(10, asyncio.TimeoutError)  

90. asyncio.current_task - 获取当前正在执行的任务。

current_task = asyncio.current_task()  
print(current_task)  

91. asyncio.sleep的超时支持 - asyncio.sleep现在接受超时参数。

try:  await asyncio.sleep(1, timeout=0.5)  # 如果超过0.5秒还没完成,则会抛出TimeoutError  
except asyncio.TimeoutError:  print("Sleep interrupted")  

92. asyncio.shield的高级用法 - 可以保护整个协程。

@asyncio.coroutine  
def protected_coroutine():  try:  await some_task()  except Exception as e:  print(f"Error occurred: {e}")  # 使用shield保护,即使外部取消任务,也会继续处理错误  asyncio.create_task(protected_coroutine())  

93. asyncio.wait的回调函数 - 使用回调函数处理完成任务。

done, _ = await asyncio.wait(tasks, callback=handle_completed_task)  

94. asyncio.gather的返回值 - 可以获取所有任务的结果。

results = await asyncio.gather(*tasks)  

95. asyncio.Queueget_nowait - 不阻塞获取队列元素。

if not queue.empty():  item = queue.get_nowait()  
else:  item = await queue.get()  

96. asyncio.Eventclear - 清除事件状态。

event.clear()  
await event.wait()  # 现在需要再次调用set()来触发  

97. asyncio.Eventis_set - 检查事件是否已设置。

if event.is_set():  print("Event is set")  

98. asyncio.subprocess.PIPE - 连接到子进程的输入/输出管道。

proc = await asyncio.create_subprocess_exec(  "python", "-c", "print('Hello from child')", stdout=asyncio.subprocess.PIPE  
)  
output, _ = await proc.communicate()  
print(output.decode())  

99. asyncio.run_coroutine_threadsafe - 在子线程中执行协程。

loop = asyncio.get_running_loop()  
future = loop.run_coroutine_threadsafe(some_async_coroutine(), thread_pool)  
result = await future.result()  

好了,今天就这些了,希望对大家有帮助。都看到这了,点个赞再走吧~

最后这里免费分享给大家一份Python全台学习资料,包含视频、源码。课件,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!
Python所有方向的学习路线图,清楚各个方向要学什么东西
100多节Python课程视频,涵盖必备基础、爬虫和数据分析
100多个Python实战案例,学习不再是只会理论
华为出品独家Python漫画教程,手机也能学习
历年互联网企业Python面试真题,复习时非常方便

这篇关于从入门到高手的99个python案例(2)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1063917

相关文章

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

Python设置Cookie永不超时的详细指南

《Python设置Cookie永不超时的详细指南》Cookie是一种存储在用户浏览器中的小型数据片段,用于记录用户的登录状态、偏好设置等信息,下面小编就来和大家详细讲讲Python如何设置Cookie... 目录一、Cookie的作用与重要性二、Cookie过期的原因三、实现Cookie永不超时的方法(一)

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提