30 个实用 Python 代码片段,30 秒内轻松学会

2024-12-31 11:28:24   小编

30 个实用 Python 代码片段,30 秒内轻松学会

Python 作为一种强大且易于学习的编程语言,拥有众多实用的代码片段,可以帮助我们快速解决各种问题。以下为您精心整理了 30 个实用的 Python 代码片段,让您在 30 秒内轻松学会!

  1. 交换两个变量的值
a, b = b, a
  1. 检查一个数是否为偶数
def is_even(n):
    return n % 2 == 0
  1. 计算列表中元素的平均值
def average(lst):
    return sum(lst) / len(lst)
  1. 反转字符串
def reverse_string(s):
    return s[::-1]
  1. 查找列表中的最大值
def find_max(lst):
    return max(lst)
  1. 计算阶乘
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)
  1. 检查一个字符串是否为回文
def is_palindrome(s):
    return s == s[::-1]
  1. 生成一个指定范围内的随机数
import random
def random_number(start, end):
    return random.randint(start, end)
  1. 计算列表中元素的和
def sum_list(lst):
    return sum(lst)
  1. 找出列表中出现次数最多的元素
from collections import Counter
def most_common(lst):
    counter = Counter(lst)
    return counter.most_common(1)[0][0]
  1. 去除列表中的重复元素
def remove_duplicates(lst):
    return list(set(lst))
  1. 对列表进行排序
def sort_list(lst):
    return sorted(lst)
  1. 计算两个数的最大公约数
def gcd(a, b):
    while b!= 0:
        a, b = b, a % b
    return a
  1. 计算两个数的最小公倍数
def lcm(a, b):
    return a * b // gcd(a, b)
  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
  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. 合并两个字典
def merge_dictionaries(dict1, dict2):
    return {**dict1, **dict2}
  1. 读取文件内容
def read_file(file_path):
    with open(file_path, 'r') as file:
        return file.read()
  1. 写入文件内容
def write_file(file_path, content):
    with open(file_path, 'w') as file:
        file.write(content)
  1. 检查文件是否存在
import os
def file_exists(file_path):
    return os.path.exists(file_path)
  1. 复制文件
import shutil
def copy_file(source_path, destination_path):
    shutil.copy(source_path, destination_path)
  1. 删除文件
import os
def delete_file(file_path):
    os.remove(file_path)
  1. 获取当前时间
import datetime
def get_current_time():
    return datetime.datetime.now()
  1. 计算程序运行时间
import time

start_time = time.time()
# 这里是您的程序代码
end_time = time.time()
execution_time = end_time - start_time
print("程序运行时间:", execution_time, "秒")
  1. 生成指定长度的随机字符串
import random
import string

def generate_random_string(length):
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(length))
  1. 列表推导式创建列表
squares = [x**2 for x in range(10)]
  1. 字典推导式创建字典
squares_dict = {x: x**2 for x in range(10)}
  1. 过滤列表中的元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
  1. 映射列表中的元素
numbers = [1, 2, 3, 4, 5]
doubled_numbers = [num * 2 for num in numbers]
  1. 遍历字典
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
    print(key, value)

这些实用的 Python 代码片段能够帮助您在日常编程中提高效率,节省时间。希望您能够熟练掌握并灵活运用它们!

TAGS: Python 编程 编程技巧 Python 代码片段 代码学习

欢迎使用万千站长工具!

Welcome to www.zzTool.com