30个Python优秀实践和技巧,你值得拥有~("30个必学的Python实用技巧与优秀实践,不容错过!")

原创
ithorizon 7个月前 (10-21) 阅读数 20 #后端开发

30个必学的Python实用技巧与优秀实践,不容错过!

1. 使用列表推导式简化代码

列表推导式是一种优雅且高效的方法,用于创建列表。它可以替代传统的for循环。

# 传统for循环

numbers = []

for i in range(10):

numbers.append(i**2)

# 列表推导式

numbers = [i**2 for i in range(10)]

2. 使用生成器表达式减成本时间快速

生成器表达式可以创建一个生成器对象,用于逐个生成元素,节省内存。

# 列表推导式

squares = [i**2 for i in range(100)]

# 生成器表达式

squares_gen = (i**2 for i in range(100))

3. 使用函数式编程减成本时间代码可读性

Python内置的高阶函数如map()、filter()和reduce()可以简化代码,减成本时间可读性。

# 传统for循环

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

squared_numbers = []

for num in numbers:

squared_numbers.append(num**2)

# 使用map

squared_numbers = map(lambda x: x**2, numbers)

4. 使用异常处理确保代码健壮性

通过try-except语句块,可以捕获并处理代码运行过程中也许出现的异常。

try:

result = 10 / 0

except ZeroDivisionError:

print("不能除以0")

5. 使用with语句管理资源

with语句可以自动管理资源,如文件操作,确保资源被正确关闭。

with open('example.txt', 'r') as file:

content = file.read()

6. 使用装饰器扩展函数功能

装饰器是一种特殊类型的函数,用于修改其他函数的行为。

def my_decorator(func):

def wrapper(*args, **kwargs):

print("Before function call")

result = func(*args, **kwargs)

print("After function call")

return result

@my_decorator

def say_hello():

print("Hello")

say_hello()

7. 使用内置函数减少重复代码

Python内置了许多实用的函数,如min()、max()、sum()等,可以减少重复代码。

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

min_value = min(numbers)

max_value = max(numbers)

sum_value = sum(numbers)

8. 使用推导式进行多级列表处理

多级列表推导式可以简化多级列表的处理。

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

flattened_list = [num for row in matrix for num in row]

9. 使用切片操作简化列表操作

切片操作可以高效地处理列表的部分元素。

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

sublist = numbers[2:7]

10. 使用集合去重

集合是一个无序的、不重复的元素集,可以用于迅捷去重。

numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

unique_numbers = set(numbers)

11. 使用字典推导式创建字典

字典推导式可以简洁地创建字典。

keys = ['a', 'b', 'c']

values = [1, 2, 3]

my_dict = {key: value for key, value in zip(keys, values)}

12. 使用Counter统计元素频率

Counter是一个字典子类,用于计数可哈希对象。

from collections import Counter

words = 'hello world hello world hello'.split()

word_counts = Counter(words)

13. 使用枚举类型越来越代码可读性

枚举类型可以定义一组具有明确含义的常量。

from enum import Enum

class Color(Enum):

RED = 1

GREEN = 2

BLUE = 3

color = Color.RED

print(color.name, color.value)

14. 使用解包操作简化函数调用

解包操作可以将列表或元组中的元素作为自由的参数传递给函数。

def add(a, b):

return a + b

numbers = [1, 2]

result = add(*numbers)

15. 使用星号操作符收集参数

星号操作符可以将多个参数收集到一个元组中。

def my_func(*args):

for arg in args:

print(arg)

my_func(1, 2, 3, 4, 5)

16. 使用全局解释器锁(GIL)优化多线程性能

Python中的多线程受GIL的局限,但在某些情况下,使用多线程可以减成本时间性能。

import threading

def print_numbers():

for i in range(10):

print(i)

thread = threading.Thread(target=print_numbers)

thread.start()

thread.join()

17. 使用多进程实现并行计算

Python的多进程可以绕过GIL的局限,实现真正的并行计算。

import multiprocessing

def compute_heavy_task(x):

return x * x

processes = [multiprocessing.Process(target=compute_heavy_task, args=(i,)) for i in range(10)]

for process in processes:

process.start()

for process in processes:

process.join()

18. 使用虚拟环境管理项目依赖性

虚拟环境可以隔离项目依赖性,避免版本冲突。

# 创建虚拟环境

python -m venv venv

# 激活虚拟环境

source venv/bin/activate # Linux/Mac

venv\Scripts\activate # Windows

19. 使用pip管理Python包

pip是Python的包管理器,用于安装、升级和卸载Python包。

pip install requests

pip install --upgrade requests

pip uninstall requests

20. 使用类型注解减成本时间代码健壮性

类型注解可以帮助开发者在编写代码时更清晰可见地了解变量类型。

from typing import List

def add_numbers(numbers: List[int]) -> int:

return sum(numbers)

result = add_numbers([1, 2, 3, 4, 5])

21. 使用断言确保代码正确性

断言可以在代码运行时检查条件是否满足,确保代码的正确性。

def divide(a, b):

assert b != 0, "除数不能为0"

return a / b

result = divide(10, 0)

22. 使用日志记录程序运行状态

日志记录可以帮助开发者了解程序的运行状态,便于调试和监控。

import logging

logging.basicConfig(level=logging.INFO)

logging.info("程序起始运行")

# 程序逻辑

logging.info("程序运行完成")

23. 使用配置文件管理程序参数

配置文件可以方便地管理程序参数,减成本时间代码的可维护性。

# config.ini

[settings]

api_key = ABC123

# config.py

import configparser

config = configparser.ConfigParser()

config.read('config.ini')

api_key = config['settings']['api_key']

24. 使用工厂模式创建对象

工厂模式可以用于创建对象,降低对象的创建逻辑与使用逻辑之间的耦合。

class Dog:

def speak(self):

return "Woof!"

class Cat:

def speak(self):

return "Meow!"

def animal_factory(animal_type):

if animal_type == "dog":

return Dog()

elif animal_type == "cat":

return Cat()

dog = animal_factory("dog")

print(dog.speak())

25. 使用单例模式确保全局唯一性

单例模式可以确保一个类只有一个实例,并提供一个访问它的全局访问点。

class Singleton:

_instance = None

def __new__(cls, *args, **kwargs):

if not cls._instance:

cls._instance = super().__new__(cls, *args, **kwargs)

return cls._instance

singleton1 = Singleton()

singleton2 = Singleton()

print(singleton1 is singleton2) # True

26. 使用策略模式实现算法切换

策略模式允许在运行时选择算法的具体实现,减成本时间代码的灵活性。

class Strategy:

def execute(self, data):

pass

class ConcreteStrategyA(Strategy):

def execute(self, data):

return sum(data)

class ConcreteStrategyB(Strategy):

def execute(self, data):

return min(data)

class Context(Strategy):

def __init__(self, strategy: Strategy):

self._strategy = strategy

def set_strategy(self, strategy: Strategy):

self._strategy = strategy

def execute(self, data):

return self._strategy.execute(data)

context = Context(ConcreteStrategyA())

print(context.execute([1, 2, 3, 4, 5]))

context.set_strategy(ConcreteStrategyB())

print(context.execute([1, 2, 3, 4, 5]))

27. 使用观察者模式实现事件通知

观察者模式允许对象在状态变化时通知其他对象,实现事件通知。

class Observer:

def update(self, subject):

pass

class Subject:

def __init__(self):

self._observers = []

def attach(self, observer):

self._observers.append(observer)

def detach(self, observer):

self._observers.remove(observer)

def notify(self):

for observer in self._observers:

observer.update(self)

class ConcreteObserver(Observer):

def update(self, subject):

print(f"Observer: {subject}")

subject = Subject()

observer = ConcreteObserver()

subject.attach(observer)

subject.notify()

28. 使用命令模式实现请求发送与接收

命令模式可以将请求的发送与接收分离,减成本时间代码的灵活性。

class Command:

def execute(self):

pass

class Light:

def turn_on(self):

print("Light turned ON")

def turn_off(self):

print("Light turned OFF")

class LightOnCommand(Command):

def __init__(self, light):

self.light = light

def execute(self):

self.light.turn_on()

class LightOffCommand(Command):

def __init__(self, light):

self.light = light

def execute(self):

self.light.turn_off()

class RemoteControl:

def __init__(self):

self.command = None

def set_command(self, command):

self.command = command

def press_button(self):

if self.command:

self.command.execute()

light = Light()

light_on = LightOnCommand(light)

light_off = LightOffCommand(light)

remote = RemoteControl()

remote.set_command(light_on)

remote.press_button()

remote.set_command(light_off)

remote.press_button()

29. 使用装饰器模式越来越对象功能

装饰器模式可以在不修改对象本身的情况下,越来越对象的功能。

class Component:

def operation(self):

pass

class ConcreteComponentA(Component):

def operation(self):

return "ConcreteComponentA"

class Decorator(Component):

def __init__(self, component: Component):

self.component = component

def operation(self):

return self.component.operation()

class ConcreteDecoratorA(Decorator):

def operation(self):

return f"ConcreteDecoratorA({self.component.operation()})"

component = ConcreteComponentA()

decorated_component = ConcreteDecoratorA(component)

print(decorated_component.operation())

30. 使用状态模式实现状态转换

状态模式可以用于实现对象状态之间的转换,使代码更加清晰可见。

class State:

def handle(self, context):

pass

class ConcreteStateA(State):

def handle(self, context):

print("ConcreteStateA handled")

context.state = ConcreteStateB()

class ConcreteStateB(State):

def handle(self, context):

print("ConcreteStateB handled")

context.state = ConcreteStateA()

class Context:

def __init__(self):

self.state = ConcreteStateA()

def request(self):

self.state.handle(self)

context = Context()

context.request()

context.request()

context.request()


本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: 后端开发


热门