Python 编程常用实例:中级进阶篇
环境变量
import os# 读取环境变量print("PATH:", os.environ["PATH"])# 设置环境变量os.environ["NEW_VAR"] = "NewValue"print("NEW_VAR:", os.environ["NEW_VAR"])说明:使用 os.environ 读取和设置环境变量。
使用 itertools 模块
import itertoolsfor combination in itertools.combinations([1, 2, 3], 2):print(combination)说明:使用 itertools 模块生成组合。
日期时间操作
from datetime import datetime, timedeltanow = datetime.utcnow()one_day = timedelta(days=1)yesterday = now - one_dayprint("Yesterday's date:", yesterday)说明:使用 datetime 模块进行日期时间计算。
列表排序和反序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]numbers.sort()print("Sorted:", numbers)numbers.reverse()print("Reversed:", numbers)说明:使用列表对象的 sort() 和 reverse() 方法进行排序和反序。
处理 JSON 数据
import jsondata = {"name": "John", "age": 30}json_data = json.dumps(data)print(json_data)parsed_data = json.loads(json_data)print(parsed_data)说明:使用 json 模块处理 JSON 数据。
使用 defaultdict
from collections import defaultdictdd = defaultdict(int)dd["apple"] = 1dd["banana"] = 2print(dd["apple"]) # 输出:1print(dd["orange"]) # 输出:0,不存在的键返回默认值0说明:使用 defaultdict 提供默认值。
使用 reduce 函数
from functools import reducefrom operator import addnumbers = [1, 2, 3, 4]total = reduce(add, numbers)print(total) # 输出:10说明:使用 reduce 函数累积地应用二元函数。
多线程编程
import threadingdef print_numbers():for i in range(10):print(i)thread = threading.Thread(target=print_numbers)thread.start()thread.join()说明:使用 threading 模块创建和管理线程。
多进程编程
from multiprocessing import Process, cpu_countdef print_hello():print("Hello from child process")if __name__ == '__main__':processes = []for _ in range(cpu_count()):p = Process(target=print_hello)p.start()processes.append(p)for p in processes:p.join()说明:使用 multiprocessing 模块进行多进程编程。
HTTP 请求
import requestsresponse = requests.get("https://www.example.com")print(response.status_code)print(response.text)说明:使用 requests 模块发送 HTTP 请求。
THE END






