Python 高手珍藏的 20 个精妙代码,短小实用价值高

2024-12-31 07:32:48   小编

Python 高手珍藏的 20 个精妙代码,短小实用价值高

在 Python 的世界里,简洁而高效的代码总是备受青睐。以下为您呈现 20 个 Python 高手珍藏的精妙代码,它们短小精悍,实用价值极高。

  1. 快速交换两个变量的值
a, b = b, a
  1. 计算列表中元素的平均值
def average(lst):
    return sum(lst) / len(lst)
  1. 检查一个数是否为偶数
def is_even(n):
    return n % 2 == 0
  1. 反转字符串
def reverse_string(s):
    return s[::-1]
  1. 生成指定范围内的随机数
import random
def random_number(start, end):
    return random.randint(start, end)
  1. 计算阶乘
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)
  1. 找出列表中的最大值
def find_max(lst):
    return max(lst)
  1. 计算列表中元素的出现次数
def count_occurrences(lst, element):
    return lst.count(element)
  1. 合并两个字典
def merge_dictionaries(dict1, dict2):
    return {**dict1, **dict2}
  1. 去除列表中的重复元素
def remove_duplicates(lst):
    return list(set(lst))
  1. 检查一个字符串是否为回文
def is_palindrome(s):
    return s == s[::-1]
  1. 对列表进行排序
lst = [5, 2, 8, 1, 9]
lst.sort()
  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. 从列表中随机抽取一个元素
import random
def random_element(lst):
    return random.choice(lst)
  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. 列表推导式生成平方数列表
squares = [i**2 for i in range(10)]
  1. 字典推导式创建新字典
numbers = [1, 2, 3, 4, 5]
square_dict = {num: num**2 for num in numbers}
  1. 读取文件并打印每一行
with open('file.txt', 'r') as file:
    for line in file:
        print(line.strip())

这些精妙的代码示例展示了 Python 语言的简洁和强大。掌握它们,将有助于您在编程中更加高效地解决问题。

TAGS: Python 高手技巧 Python 实用代码 Python 精妙代码 Python 代码珍藏

欢迎使用万千站长工具!

Welcome to www.zzTool.com