编程 Python 中提升生产力的 12 个代码示例

2024-11-18 11:34:55 +0800 CST views 550

Python 中提升生产力的 12 个代码示例

1. 列表推导式:简化循环操作

列表推导式是一种快速创建列表的方法,使代码更加简洁。

# 普通方法
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = []
for number in numbers:
    if number % 2 == 0:
        even_numbers.append(number)
print(even_numbers)  # 输出: [2, 4, 6, 8]

# 使用列表推导式
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)  # 输出: [2, 4, 6, 8]

2. 字典推导式:处理字典数据

字典推导式可以帮助快速创建或修改字典。

words = ['apple', 'banana', 'cherry']
word_lengths = {word: len(word) for word in words}
print(word_lengths)  # 输出: {'apple': 5, 'banana': 6, 'cherry': 6}

3. 生成器表达式:节省内存

生成器表达式返回一个迭代器对象,节省内存。

# 列表推导式
squares = [x**2 for x in range(100000)]
print(squares[0:10])

# 生成器表达式
squares_gen = (x**2 for x in range(100000))
print(next(squares_gen))  # 输出: 0
print(next(squares_gen))  # 输出: 1
print(next(squares_gen))  # 输出: 4

4. 使用 enumerate():简化索引操作

enumerate() 函数可以在循环中获取元素和索引。

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

5. 使用 zip():并行迭代多个序列

zip() 函数用于并行遍历多个序列。

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old.")

6. 使用 itertools 模块:高效处理迭代操作

itertools.cycle() 可以创建一个无限循环的迭代器。

import itertools

colors = ['red', 'green', 'blue']
color_cycle = itertools.cycle(colors)

for _ in range(10):
    print(next(color_cycle))

7. 使用 collections 模块:高效处理容器类型

Counter 可以轻松统计列表中元素的出现次数。

from collections import Counter

words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
word_counts = Counter(words)
print(word_counts)  # 输出: Counter({'apple': 3, 'banana': 2, 'cherry': 1})

8. 使用 functools 模块:提高函数灵活性

functools.partial() 用于部分应用函数的参数。

from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, base=2)
print(square(exponent=3))  # 输出: 8
print(square(exponent=4))  # 输出: 16

9. 使用 contextlib 模块:管理上下文

contextlib.contextmanager 用于创建上下文管理器。

from contextlib import contextmanager

@contextmanager
def open_file(file_path, mode='r'):
    file = open(file_path, mode)
    try:
        yield file
    finally:
        file.close()

with open_file('example.txt') as file:
    content = file.read()
    print(content)

10. 使用 pathlib 模块:简化文件路径操作

pathlib 提供了更直观的文件路径操作。

from pathlib import Path

directory = Path('test_directory')
directory.mkdir(exist_ok=True)

file_path = directory / 'example.txt'
file_path.touch()

with file_path.open('r') as file:
    content = file.read()
    print(content)

file_path.unlink()
directory.rmdir()

11. 使用 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')

12. 使用 pandas 库:高效处理数据

pandas 提供了强大的数据处理功能。

import pandas as pd

data = pd.read_csv('example.csv')
print(data.head())

filtered_data = data[data['column_name'] > 10]
grouped_data = data.groupby('category').sum()

filtered_data.to_csv('filtered_example.csv', index=False)

实战案例:分析销售数据

使用 Pandas 处理销售数据的案例。

步骤 1:读取数据

sales_data = pd.read_csv('sales_data.csv')
print(sales_data.head())

步骤 2:筛选数据

threshold = 100000
filtered_sales = sales_data[sales_data['sales'] > threshold]
print(filtered_sales)

步骤 3:分组和聚合

monthly_sales = sales_data.groupby('month').sum()['sales']
print(monthly_sales)

步骤 4:保存结果

filtered_sales.to_csv('filtered_sales_data.csv', index=False)

推荐文章

js一键生成随机颜色:randomColor
2024-11-18 10:13:44 +0800 CST
Golang在整洁架构中优雅使用事务
2024-11-18 19:26:04 +0800 CST
Golang 几种使用 Channel 的错误姿势
2024-11-19 01:42:18 +0800 CST
SQL常用优化的技巧
2024-11-18 15:56:06 +0800 CST
PHP 压缩包脚本功能说明
2024-11-19 03:35:29 +0800 CST
Boost.Asio: 一个美轮美奂的C++库
2024-11-18 23:09:42 +0800 CST
Python设计模式之工厂模式详解
2024-11-19 09:36:23 +0800 CST
在Vue3中实现代码分割和懒加载
2024-11-17 06:18:00 +0800 CST
php 连接mssql数据库
2024-11-17 05:01:41 +0800 CST
利用Python构建语音助手
2024-11-19 04:24:50 +0800 CST
黑客帝国代码雨效果
2024-11-19 01:49:31 +0800 CST
ElasticSearch集群搭建指南
2024-11-19 02:31:21 +0800 CST
php指定版本安装php扩展
2024-11-19 04:10:55 +0800 CST
程序员茄子在线接单