Python语法与常用用法(3)

Python语法与常用用法(3)


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"))

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值