收集 9999 种写 Python 的技巧

1. 嵌套 list 合并

1
2
3
4
5
nested_list = [[1, 2], [3, 4]]

# 使用 sum() 函数和列表推导式
merged_list = sum(nested_list, [])
print(merged_list)  # 输出: [1, 2, 3, 4]

sum() 函数的第一个参数是要求和的可迭代对象(在本例中是 nested_list)。第二个参数是初始值,这里我们使用一个空列表 []

sum() 函数会将 nested_list 中的每个子列表展开,并将它们的元素累加到初始值 [] 中,从而得到一个扁平化的列表。

2. 打日志

1
2
3
4
import logging

# 配置日志记录器
logging.basicConfig(filename='./error.log', level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s')

3. dict 的 get() 方法

当您不确定键是否存在时,可以使用 get() 方法,它可以提供一个默认值,以防该键不存在。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import json

json_data = '{"name": "Alice", "age": 25}'
data = json.loads(json_data)

# 获取 "name" 元素,如果不存在则返回 "Unknown"
name = data.get("name", "Unknown")
print(name)  # Output: Alice

# 获取 "gender" 元素,如果不存在则返回 "Unknown"
gender = data.get("gender", "Unknown")
print(gender)  # Output: Unknown

4. pandas 操作表格

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import pandas as pd

# 创建一个数据字典
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'London', 'Paris']
}

# 创建一个 DataFrame
df = pd.DataFrame(data)

# 将 DataFrame 写入 Excel 文件
df.to_excel('output.xlsx', index=False)

5. 多进程

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import multiprocessing

def my_function(arg):
    # 模拟一些计算任务
    result = [arg * i for i in range(5)]
    return result

if __:
    # 创建进程池
    with multiprocessing.Pool() as pool:
        # 异步调用 my_function 并收集结果
        results = pool.map(my_function, [1, 2, 3])

    # 打印结果
    for result in results:
        print(result)

6. HTTP

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import requests

# 定制 header
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your_access_token'
}

params = {
    'test': 'xx'
}

# 发起 GET 请求
response = requests.get('https://api.example.com/data', headers=headers, params)

# 检查请求状态码
if response.status_code != 200:
    print(f'Request failed with status code: {response.status_code}')
data = response.json()

交流群
解忧随笔交流群

原文链接: https://rustyscript.com/posts/tech/python/collect-9999-tips-for-writing-python/

Buy me a coffee~
室长 支付宝支付宝
室长 微信微信
0%