必藏!20 个超实用的 Python 代码示例

2024-12-31 05:09:44   小编

必藏!20 个超实用的 Python 代码示例

Python 作为一种广泛应用的编程语言,拥有丰富的功能和强大的库。以下为您带来 20 个超实用的 Python 代码示例,涵盖了不同的应用场景,帮助您提升编程技能。

示例 1:检查一个数是否为质数

def is_prime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

示例 2:计算斐波那契数列

def fibonacci(n):
    fib_seq = [0, 1]
    while len(fib_seq) < n:
        fib_seq.append(fib_seq[-1] + fib_seq[-2])
    return fib_seq

示例 3:实现冒泡排序

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]
    return arr

示例 4:文件读写操作

# 写入文件
def write_to_file(file_path, content):
    with open(file_path, 'w') as f:
        f.write(content)

# 读取文件
def read_from_file(file_path):
    with open(file_path, 'r') as f:
        content = f.read()
    return content

示例 5:生成随机密码

import random
import string

def generate_password(length=8):
    all_characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(all_characters) for i in range(length))
    return password

示例 6:字符串反转

def reverse_string(s):
    return s[::-1]

示例 7:计算两个数的最大公约数

def gcd(a, b):
    while b!= 0:
        a, b = b, a % b
    return a

示例 8:列表去重

def remove_duplicates(lst):
    return list(set(lst))

示例 9:计算阶乘

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

示例 10:计算平均数

def average(numbers):
    return sum(numbers) / len(numbers)

示例 11:判断闰年

def is_leap_year(year):
    if (year % 4 == 0 and year % 100!= 0) or year % 400 == 0:
        return True
    else:
        return False

示例 12:矩阵转置

def transpose_matrix(matrix):
    return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

示例 13:二分查找

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

示例 14:合并两个已排序的列表

def merge_sorted_lists(list1, list2):
    merged_list = []
    i = j = 0

    while i < len(list1) and j < len(list2):
        if list1[i] < list2[j]:
            merged_list.append(list1[i])
            i += 1
        else:
            merged_list.append(list2[j])
            j += 1

    merged_list.extend(list1[i:])
    merged_list.extend(list2[j:])

    return merged_list

示例 15:找出列表中的最大值和最小值

def find_max_min(lst):
    return max(lst), min(lst)

示例 16:计算列表元素之和

def sum_of_list(lst):
    return sum(lst)

示例 17:字符串分割

def split_string(s, delimiter):
    return s.split(delimiter)

示例 18:字典的创建和操作

# 创建字典
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# 访问字典中的值
print(my_dict['name'])

# 修改字典中的值
my_dict['age'] = 26

# 添加新的键值对
my_dict['occupation'] = 'Engineer'

# 删除键值对
del my_dict['city']

示例 19:生成随机数

import random

def generate_random_number(start, end):
    return random.randint(start, end)

示例 20:简单的 Web 服务器

import http.server
import socketserver

PORT = 8080

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print(f"Serving at port {PORT}")
    httpd.serve_forever()

以上就是为您精心整理的 20 个超实用的 Python 代码示例,希望对您的学习和工作有所帮助。不断练习和应用这些示例,您将更加熟练地掌握 Python 编程。

TAGS: Python 实用技巧 Python 代码示例 必藏干货 超实用 Python

欢迎使用万千站长工具!

Welcome to www.zzTool.com