Python语法与常用用法(3)
文章目录
- Python语法与常用用法(3)
- 51. `any()` 和 `all()` 函数:
- 52. `property` 装饰器:
- 53. 单例模式:
- 54. 使用 `functools.wraps` 保留函数元信息:
- 55. 使用 `collections.ChainMap` 合并字典:
- 56. 解构赋值:
- 57. 使用 `zip` 和 `*` 解压缩序列:
- 58. `collections.Counter` 的高级用法:
- 59. 使用 `contextlib.suppress` 忽略特定异常:
- 60. 使用 `collections.defaultdict` 的工厂方法:
- 61. 使用 `deque` 实现高效的队列操作:
- 62. 使用 `__slots__` 节省内存:
- 63. 使用 `unittest` 编写测试:
- 64. 了解 Python 内存管理:
- 65. 使用 `functools.lru_cache` 进行缓存:
- 66. 使用 `re` 模块进行正则表达式操作:
- 67. 使用 `functools.partial` 创建可定制的函数:
- 68. 使用 `logging` 模块进行日志记录:
- 69. 使用 `contextlib.ExitStack` 管理多个文件:
- 70. 使用 `bisect` 模块进行二分查找:
- 71. 使用 `functools.reduce` 进行累积操作:
- 72. 使用 `asyncio.gather` 并发运行多个协程:
- 73. 使用 `pathlib` 模块处理路径:
- 74. 使用 `requests` 库进行 HTTP 请求:
- 75. 使用 `cProfile` 进行性能分析:
- 76. 使用 `queue` 模块实现线程安全的队列:
- 77. 使用 `warnings` 模块管理警告:
- 78. 使用 `uuid` 模块生成唯一标识符:
- 79. 使用 `deque` 实现固定大小的队列:
- 80. 使用 `base64` 模块进行编码和解码:
51. any()
和 all()
函数:
# 使用 any() 和 all() 函数
my_list = [True, False, True, True]
# any() 检查是否至少有一个为 True
print(any(my_list)) # True
# all() 检查是否全部为 True
print(all(my_list)) # False
52. property
装饰器:
# 使用 property 装饰器创建属性
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def diameter(self):
return self._radius * 2
circle = Circle(5)
print(circle.diameter)
53. 单例模式:
# 使用单例模式
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
# 创建实例
instance1 = Singleton()
instance2 = Singleton()
print(instance1 is instance2) # True
54. 使用 functools.wraps
保留函数元信息:
# 使用 functools.wraps 保留函数元信息
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper():
"""Wrapper function"""
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():
"""Prints a greeting"""
print("Hello!")
print(say_hello.__name__) # 输出 say_hello
print(say_hello.__doc__) # 输出 Prints a greeting
55. 使用 collections.ChainMap
合并字典:
# 使用 collections.ChainMap 合并字典
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict(ChainMap(dict1, dict2))
print(merged_dict)
# 结果: {'a': 1, 'b': 2, 'c': 4}
56. 解构赋值:
# 解构赋值
point = (3, 5)
x, y = point
print(x, y)
57. 使用 zip
和 *
解压缩序列:
# 使用 zip 和 * 解压缩序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
# 使用 zip 打包两个序列
zipped_data = zip(names, ages)
# 使用 * 解压缩序列
unzipped_names, unzipped_ages = zip(*zipped_data)
print(unzipped_names)
print(unzipped_ages)
58. collections.Counter
的高级用法:
# Counter 的高级用法
from collections import Counter
text = "python is powerful and python is easy to learn"
word_counts = Counter(text.split())
# 查找最常见的两个单词
common_words = word_counts.most_common(2)
print(common_words)
59. 使用 contextlib.suppress
忽略特定异常:
# 使用 contextlib.suppress 忽略特定异常
from contextlib import suppress
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
# 使用 suppress 忽略异常
with suppress(ZeroDivisionError):
result = 10 / 0
print("This will be skipped.")
60. 使用 collections.defaultdict
的工厂方法:
# defaultdict 的工厂方法
from collections import defaultdict
# 使用 int 作为默认工厂方法
counter = defaultdict(int)
numbers = [1, 2, 3, 1, 2, 3, 4, 1]
# 统计每个数字的出现次数
for number in numbers:
counter[number] += 1
print(counter)
61. 使用 deque
实现高效的队列操作:
# 使用 deque 实现高效的队列操作
from collections import deque
my_queue = deque([1, 2, 3, 4])
# 左边插入元素
my_queue.appendleft(0)
# 右边弹出元素
item = my_queue.pop()
print(my_queue)
print(item)
62. 使用 __slots__
节省内存:
# 使用 __slots__ 节省内存
class Point:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
point = Point(3, 5)
print(point.x, point.y)
63. 使用 unittest
编写测试:
# 使用 unittest 编写测试
import unittest
def add_numbers(a, b):
return a + b
class TestAddNumbers(unittest.TestCase):
def test_add_positive_numbers(self):
result = add_numbers(3, 5)
self.assertEqual(result, 8)
if __name__ == "__main__":
unittest.main()
64. 了解 Python 内存管理:
# 了解 Python 内存管理
import sys
# 获取对象占用内存的大小
my_list = [1, 2, 3, 4, 5]
size = sys.getsizeof(my_list)
print(size)
65. 使用 functools.lru_cache
进行缓存:
# 使用 functools.lru_cache 进行缓存
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
result = fibonacci(10)
print(result)
66. 使用 re
模块进行正则表达式操作:
# 使用 re 模块进行正则表达式操作
import re
text = "Python is fun and Python is powerful"
# 查找所有以大写字母开头的单词
pattern = r'\b[A-Z][a-z]*\b'
matches = re.findall(pattern, text)
print(matches)
67. 使用 functools.partial
创建可定制的函数:
# 使用 functools.partial 创建可定制的函数
from functools import partial
def power(base, exponent):
return base ** exponent
# 创建一个计算平方的函数
square = partial(power, exponent=2)
result = square(4)
print(result)
68. 使用 logging
模块进行日志记录:
# 使用 logging 模块进行日志记录
import logging
# 配置日志记录
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# 记录日志
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
69. 使用 contextlib.ExitStack
管理多个文件:
# 使用 contextlib.ExitStack 管理多个上下文管理器
from contextlib import ExitStack
with ExitStack() as stack:
file1 = stack.enter_context(open('file1.txt', 'r'))
file2 = stack.enter_context(open('file2.txt', 'r'))
# 使用 file1 和 file2
70. 使用 bisect
模块进行二分查找:
# 使用 bisect 模块进行二分查找
import bisect
sorted_list = [1, 3, 5, 7, 9]
# 在有序列表中插入元素并保持排序
bisect.insort(sorted_list, 6)
print(sorted_list)
# 结果:[1, 3, 5, 6, 7, 9]
71. 使用 functools.reduce
进行累积操作:
# 使用 functools.reduce 进行累积操作
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# 计算所有数字的累积乘积
product = reduce(lambda x, y: x * y, numbers)
print(product)
# 结果:120
72. 使用 asyncio.gather
并发运行多个协程:
# 使用 asyncio.gather 并发运行多个协程
import asyncio
async def coroutine1():
await asyncio.sleep(2)
print("Coroutine 1")
async def coroutine2():
await asyncio.sleep(1)
print("Coroutine 2")
async def main():
await asyncio.gather(coroutine1(), coroutine2())
asyncio.run(main())
或者:
# 使用 asyncio 创建协程并发
import asyncio
async def coroutine1():
print("Coroutine 1")
async def coroutine2():
print("Coroutine 2")
# 创建事件循环
loop = asyncio.get_event_loop()
# 并发运行多个协程
tasks = [coroutine1(), coroutine2()]
loop.run_until_complete(asyncio.gather(*tasks))
73. 使用 pathlib
模块处理路径:
# 使用 pathlib 模块处理路径
from pathlib import Path
# 创建路径对象
path = Path('my_directory')
# 检查路径是否存在
if not path.exists():
path.mkdir()
# 遍历目录中的文件
for file in path.iterdir():
print(file)
74. 使用 requests
库进行 HTTP 请求:
# 使用 requests 库进行 HTTP 请求
import requests
# 发送 GET 请求
response = requests.get('https://www.example.com')
# 打印响应内容
print(response.text)
75. 使用 cProfile
进行性能分析:
# 使用 cProfile 进行性能分析
import cProfile
def my_function():
for _ in range(1000000):
_ = 2 + 2
# 运行性能分析
cProfile.run('my_function()')
76. 使用 queue
模块实现线程安全的队列:
# 使用 queue 模块实现线程安全的队列
import queue
import threading
# 创建队列
my_queue = queue.Queue()
def worker():
while True:
item = my_queue.get()
if item is None:
break
# 处理 item
# 启动线程
thread = threading.Thread(target=worker)
thread.start()
# 将任务加入队列
my_queue.put("Task 1")
my_queue.put("Task 2")
# 停止线程
my_queue.put(None)
thread.join()
77. 使用 warnings
模块管理警告:
# 使用 warnings 模块管理警告
import warnings
def deprecated_function():
warnings.warn("This function is deprecated", DeprecationWarning)
# 函数的实际操作
deprecated_function()
78. 使用 uuid
模块生成唯一标识符:
# 使用 uuid 模块生成唯一标识符
import uuid
unique_id = uuid.uuid4()
print(unique_id)
79. 使用 deque
实现固定大小的队列:
# 使用 deque 实现固定大小的队列
from collections import deque
max_size = 3
my_queue = deque(maxlen=max_size)
my_queue.append(1)
my_queue.append(2)
my_queue.append(3)
print(my_queue)
my_queue.append(4) # 超过最大大小,将删除最旧的元素
print(my_queue)
80. 使用 base64
模块进行编码和解码:
# 使用 base64 模块进行编码和解码
import base64
# 编码字符串
encoded_data = base64.b64encode(b"Hello, World!")
print(encoded_data)
# 解码字符串
decoded_data = base64.b64decode(encoded_data)
print(decoded_data.decode("utf-8"))