IT袋

当前位置:主页 > 经验教程 > 建站编程 >

45个Python实用小技巧

45个Python实用小技巧(3)

时间:2023-12-13 13:25:23 来源:IT袋 作者:马勇
导读:45个Python实用小技巧,28、JSON数据处理 import json# 将Python对象转换成JSONjson_data = json.dumps({"name": "John", "age": 25})# 将JSON转换成Python对象python_obj = json.loads(json_data) 29、Python修饰符

45个Python实用小技巧

28、JSON数据处理

import json
# 将Python对象转换成JSON
json_data = json.dumps({"name": "John", "age": 25})
# 将JSON转换成Python对象
python_obj = json.loads(json_data)

29、Python修饰符

def decorator(func):
    def wrapper():
        print("Before function execution")
        func()
        print("After function execution")
    return wrapper
@decorator
def my_function():
    print("Inside the function")
my_function()

30、使用枚举

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
print(Color.RED)

31、集合操作

set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 合并
union_set = set1 | set2
# 交集
intersection_set = set1 & set2
# 差值
difference_set = set1 - set2

32、列表推导式

numbers = [1, 2, 3, 4, 5]
# 偶数的平方
squares = [x**2 for x in numbers if x % 2 == 0]

33、匿名函数

add = lambda x, y: x + y
result = add(3, 5)

34、线程与Concurrent.futures

from concurrent.futures import ThreadPoolExecutor
def square(x):
    return x**2
with ThreadPoolExecutor() as executor:
    results = executor.map(square, [1, 2, 3, 4, 5])

35、使用gettext国际化

import gettext
# 设置语言
lang = 'en_US'
_ = gettext.translation('messages', localedir='locale', languages=[lang]).gettext
print(_("Hello, World!"))

36、虚拟环境

# 创建一个虚拟环境
python -m venv myenv
# 激活虚拟环境
source myenv/bin/activate  # On Unix or MacOS
myenv\Scripts\activate  # On Windows
# 退出虚拟环境
deactivate

37、日期处理

from datetime import datetime, timedelta
now = datetime.now()
# 日期格式化
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# 添加天数
future_date = now + timedelta(days=7)

38、使用字典

my_dict = {'name': 'John', 'age': 30}
# 获取值
age = my_dict.get('age', 25)
# 遍历键和键值
for key, value in my_dict.items():
    print(f"{key}: {value}")

39、正则表达式

import re
text = "Hello, 123 World!"
# 匹配数字
numbers = re.findall(r'\d+', text)

40、迭代器

def square_numbers(n):
    for i in range(n):
        yield i**2
squares = square_numbers(5)

41、与SQLite的数据库交互

import sqlite3
# 链接SQLite数据库
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# 执行SQL查询语句
cursor.execute('SELECT * FROM mytable')

42、ZIP文件操作处理

import zipfile
with zipfile.ZipFile('archive.zip', 'w') as myzip:
    myzip.write('file.txt')
with zipfile.ZipFile('archive.zip', 'r') as myzip:
    myzip.extractall('extracted')

相关阅读