25 个极具价值的 Python 代码段

2024-12-31 10:51:11   小编

25 个极具价值的 Python 代码段

在 Python 编程的世界里,掌握一些实用的代码段可以极大地提高工作效率和编程能力。以下为您介绍 25 个极具价值的 Python 代码段。

  1. 列表推导式
squares = [i**2 for i in range(10)]
  1. 字典推导式
even_squares = {i: i**2 for i in range(10) if i % 2 == 0}
  1. 生成斐波那契数列
def fibonacci(n):
    fib_seq = [0, 1]
    while len(fib_seq) < n:
        fib_seq.append(fib_seq[-1] + fib_seq[-2])
    return fib_seq
  1. 反转字符串
string = "Hello, World!"
reversed_string = string[::-1]
  1. 计算平均值
numbers = [1, 2, 3, 4, 5]
average = sum(numbers) / len(numbers)
  1. 检查回文
def is_palindrome(string):
    return string == string[::-1]
  1. 合并两个字典
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
  1. 过滤列表中的奇数
numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0]
  1. 计算阶乘
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)
  1. 字符串格式化
name = "Alice"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))
  1. 冒泡排序
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1] :
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
  1. 快速排序
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)
  1. 二分查找
def binary_search(arr, x):
    low = 0
    high = len(arr) - 1

    while low <= high:
        mid = (low + high) // 2

        if arr[mid] == x:
            return mid
        elif arr[mid] < x:
            low = mid + 1
        else:
            high = mid - 1

    return -1
  1. 读取文件
with open('file.txt', 'r') as file:
    content = file.read()
  1. 写入文件
with open('file.txt', 'w') as file:
    file.write('Hello, World!')
  1. 异常处理
try:
    result = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
  1. 计算运行时间
import time

start_time = time.time()
# Your code here
end_time = time.time()
execution_time = end_time - start_time
print("Execution time: ", execution_time)
  1. 生成随机数
import random
random_number = random.randint(1, 100)
  1. 线程创建
import threading

def thread_function(name):
    print("Thread %s is running" % name)

thread = threading.Thread(target=thread_function, args=("Thread 1",))
thread.start()
  1. 进程创建
import multiprocessing

def process_function(name):
    print("Process %s is running" % name)

process = multiprocessing.Process(target=process_function, args=("Process 1",))
process.start()
  1. 网络请求
import requests
response = requests.get('https://www.example.com')
  1. 数据序列化
import json
data = {'name': 'Alice', 'age': 25}
json_data = json.dumps(data)
  1. 数据反序列化
import json
json_string = '{"name": "Alice", "age": 25}'
data = json.loads(json_string)
  1. 装饰器
def my_decorator(func):
    def wrapper():
        print("Before function execution")
        func()
        print("After function execution")
    return wrapper

@my_decorator
def my_function():
    print("Hello, World!")
  1. 类的继承
class ParentClass:
    def parent_method(self):
        print("Parent method")

class ChildClass(ParentClass):
    def child_method(self):
        print("Child method")

这些 Python 代码段涵盖了各种常见的编程任务和技巧,熟练掌握它们将有助于您更高效地进行 Python 编程。

TAGS: Python 编程 代码示例 Python 代码段 极具价值

欢迎使用万千站长工具!

Welcome to www.zzTool.com