📋 22. 常用代码片段100+
本章概述
收集 Python 开发中最常用的代码片段,方便复制粘贴使用。 预计学习时间:浏览即可,需要时查阅
1. 数字相关
# 1. 判断奇偶
def is_even(n):
return n % 2 == 0
# 2. 判断素数
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# 3. 斐波那契数列
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# 4. 最大公约数
def gcd(a, b):
while b:
a, b = b, a % b
return a
# 5. 最小公倍数
def lcm(a, b):
return a * b // gcd(a, b)
# 6. 阶乘
def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
# 7. 十进制转二进制
def dec_to_bin(n):
return bin(n)[2:]
# 8. 保留n位小数
def round_n(num, n=2):
return round(num, n)
# 9. 生成随机数
import random
random.randint(1, 100) # 1~100的随机整数
random.random() # 0~1的随机浮点数
random.uniform(1, 10) # 1~10的随机浮点数
# 10. 数学计算
import math
math.sqrt(16) # 开平方
math.pi # 圆周率
math.e # 自然常数
math.log(100, 10) # 对数
math.sin(math.pi/2) # 正弦2. 字符串相关
# 11. 反转字符串
s = "hello"
s[::-1] # 'olleh'
# 12. 判断回文
def is_palindrome(s):
return s == s[::-1]
# 13. 统计字符出现次数
s = "hello world"
s.count('l') # 3
# 14. 字符串转列表
list("hello") # ['h', 'e', 'l', 'l', 'o']
# 15. 列表转字符串
lst = ['h', 'e', 'l', 'l', 'o']
''.join(lst) # 'hello'
# 16. 去除空白
s = " hello "
s.strip() # 去除两端空白
s.lstrip() # 去除左端空白
s.rstrip() # 去除右端空白
# 17. 大小写转换
s = "Hello World"
s.upper() # 全大写 'HELLO WORLD'
s.lower() # 全小写 'hello world'
s.title() # 首字母大写 'Hello World'
s.capitalize() # 第一个字母大写 'Hello world'
# 18. 判断开头结尾
s = "hello.txt"
s.startswith("hello") # True
s.endswith(".txt") # True
# 19. 分割字符串
s = "a,b,c,d"
s.split(",") # ['a', 'b', 'c', 'd']
# 20. 替换字符串
s = "hello world"
s.replace("world", "python") # 'hello python'
# 21. 字符串填充
s = "hello"
s.center(10, '-') # '--hello---' 居中填充
s.ljust(10, '-') # 'hello-----' 左对齐填充
s.rjust(10, '-') # '-----hello' 右对齐填充
s.zfill(10) # '00000hello' 前面补0
# 22. 查找子串
s = "hello world"
s.find("world") # 6(找到返回索引)
s.find("python") # -1(没找到返回-1)
s.index("world") # 6(找到返回索引)
# s.index("python") # 没找到报错
# 23. 判断字符串内容
s = "12345"
s.isdigit() # 是否全是数字
s.isalpha() # 是否全是字母
s.isalnum() # 是否全是字母或数字
s.isspace() # 是否全是空白
s.islower() # 是否全小写
s.isupper() # 是否全大写
# 24. 字符串格式化
name = "Tom"
age = 18
# f-string(推荐)
f"我叫{name},今年{age}岁"
# format
"我叫{},今年{}岁".format(name, age)
# % 格式化
"我叫%s,今年%d岁" % (name, age)
# 25. 多行字符串
s = """第一行
第二行
第三行"""3. 列表相关
# 26. 列表去重(保持顺序)
lst = [1, 2, 2, 3, 3, 3, 4]
list(dict.fromkeys(lst)) # [1, 2, 3, 4]
# 27. 列表去重(不保持顺序,更快)
list(set(lst))
# 28. 统计元素出现次数
lst = [1, 2, 2, 3, 3, 3]
lst.count(3) # 3
# 29. 找出出现次数最多的元素
from collections import Counter
lst = [1, 2, 2, 3, 3, 3]
Counter(lst).most_common(1) # [(3, 3)]
# 30. 列表排序
lst = [3, 1, 4, 1, 5, 9]
sorted(lst) # 升序
sorted(lst, reverse=True) # 降序
# 31. 按自定义规则排序
words = ["apple", "banana", "cherry"]
sorted(words, key=len) # 按长度排序
# 32. 列表反转
lst = [1, 2, 3]
lst[::-1] # 不修改原列表
lst.reverse() # 修改原列表
# 33. 列表推导式
# 生成平方列表
[x**2 for x in range(10)]
# 带条件的列表推导式
[x**2 for x in range(10) if x % 2 == 0]
# 34. 嵌套列表展开
lst = [[1, 2], [3, 4], [5, 6]]
[x for sublist in lst for x in sublist]
# [1, 2, 3, 4, 5, 6]
# 35. 同时遍历索引和值
lst = ["a", "b", "c"]
for i, val in enumerate(lst):
print(i, val)
# 36. 同时遍历多个列表
names = ["张三", "李四"]
ages = [18, 19]
for name, age in zip(names, ages):
print(name, age)
# 37. 列表所有元素的和/最大/最小
sum(lst) # 和
max(lst) # 最大值
min(lst) # 最小值
# 38. 判断列表是否有重复
len(lst) == len(set(lst)) # True表示没有重复
# 39. 复制列表
lst = [1, 2, 3]
lst.copy() # 方法1
lst[:] # 方法2
list(lst) # 方法3
# 40. 扩展列表
lst = [1, 2, 3]
lst.extend([4, 5, 6]) # [1, 2, 3, 4, 5, 6]4. 字典相关
# 41. 字典合并(Python 3.9+)
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
d = {**d1, **d2} # 方法1
d = d1 | d2 # 方法2(Python 3.9+)
# 42. 安全获取字典值
d = {"name": "Tom", "age": 18}
d.get("name") # 'Tom'
d.get("gender", "男") # '男'(默认值)
# 43. 遍历字典
d = {"a": 1, "b": 2, "c": 3}
# 遍历key
for key in d:
print(key)
# 遍历value
for value in d.values():
print(value)
# 遍历key和value
for key, value in d.items():
print(key, value)
# 44. 字典推导式
{x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 45. 按值排序字典
d = {"a": 3, "b": 1, "c": 2}
sorted(d.items(), key=lambda x: x[1])
# [('b', 1), ('c', 2), ('a', 3)]
# 46. 找出字典中最大值的key
d = {"a": 3, "b": 1, "c": 2}
max(d, key=d.get) # 'a'
# 47. 交换字典的key和value
d = {"a": 1, "b": 2, "c": 3}
{v: k for k, v in d.items()}
# {1: 'a', 2: 'b', 3: 'c'}
# 48. 字典设置默认值
d = {}
d.setdefault("count", 0)
d["count"] += 1 # d = {'count': 1}
# 49. 计数器(统计频率)
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = Counter(words)
# Counter({'apple': 3, 'banana': 2, 'cherry': 1})
# 50. 默认字典
from collections import defaultdict
d = defaultdict(list)
d["fruits"].append("apple") # 不用先判断key是否存在5. 文件相关
# 51. 读取整个文件
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read()
# 52. 逐行读取文件
with open("file.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
# 53. 读取所有行到列表
with open("file.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
# 54. 写入文件
with open("file.txt", "w", encoding="utf-8") as f:
f.write("Hello World\n")
f.write("你好,世界\n")
# 55. 追加写入
with open("file.txt", "a", encoding="utf-8") as f:
f.write("追加的内容\n")
# 56. 写入列表到文件
lines = ["第一行", "第二行", "第三行"]
with open("file.txt", "w", encoding="utf-8") as f:
f.write("\n".join(lines))
# 57. 复制文件
import shutil
shutil.copy("src.txt", "dst.txt")
# 58. 判断文件是否存在
import os
os.path.exists("file.txt")
os.path.isfile("file.txt") # 是否是文件
os.path.isdir("dir") # 是否是目录
# 59. 获取文件大小
import os
size = os.path.getsize("file.txt") # 字节数
# 60. 列出目录内容
import os
files = os.listdir(".") # 列出当前目录
# 61. 创建目录
import os
os.mkdir("new_dir") # 创建单级目录
os.makedirs("a/b/c") # 创建多级目录
# 62. 删除文件/目录
import os
os.remove("file.txt") # 删除文件
os.rmdir("dir") # 删除空目录
import shutil
shutil.rmtree("dir") # 删除非空目录(危险!)
# 63. 重命名文件
import os
os.rename("old.txt", "new.txt")
# 64. 获取文件扩展名
import os
name, ext = os.path.splitext("file.txt")
# name = 'file', ext = '.txt'
# 65. 路径拼接
import os
path = os.path.join("dir", "subdir", "file.txt")6. 日期时间相关
# 66. 获取当前时间
from datetime import datetime
now = datetime.now()
print(now)
# 67. 格式化时间
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M:%S")
# '2024-01-01 12:00:00'
# 68. 字符串转时间
s = "2024-01-01 12:00:00"
d = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
# 69. 时间加减
from datetime import timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
yesterday = now - timedelta(days=1)
next_hour = now + timedelta(hours=1)
# 70. 计算时间差
from datetime import datetime
d1 = datetime(2024, 1, 1)
d2 = datetime(2024, 12, 31)
diff = d2 - d1
print(diff.days) # 天数
print(diff.total_seconds()) # 总秒数
# 71. 获取今天日期
from datetime import date
today = date.today()
print(today) # 2024-01-01
# 72. 获取星期几
from datetime import date
today = date.today()
today.weekday() # 0=周一, 6=周日
today.isoweekday() # 1=周一, 7=周日
# 73. 时间戳转日期
import time
timestamp = time.time() # 当前时间戳
dt = datetime.fromtimestamp(timestamp)
# 74. 日期转时间戳
dt = datetime.now()
timestamp = dt.timestamp()
# 75. 程序计时
import time
start = time.time()
# ... 你的代码 ...
end = time.time()
print(f"耗时:{end - start:.4f}秒")7. 正则表达式
import re
# 76. 匹配(从头开始)
result = re.match(r"\d+", "123abc")
if result:
print(result.group())
# 77. 搜索(任意位置)
result = re.search(r"\d+", "abc123def")
if result:
print(result.group())
# 78. 查找所有
results = re.findall(r"\d+", "a1b2c3")
print(results) # ['1', '2', '3']
# 79. 替换
result = re.sub(r"\d+", "X", "a1b2c3")
print(result) # aXbXcX
# 80. 分割
result = re.split(r"\d+", "a1b2c3")
print(result) # ['a', 'b', 'c', '']
# 81. 常用正则模式
# 数字
r"\d+" # 数字
r"\D+" # 非数字
# 字母
r"[a-zA-Z]+" # 字母
r"\w+" # 字母数字下划线
# 空白
r"\s+" # 空白字符
r"\S+" # 非空白字符
# 邮箱
r"[\w.-]+@[\w.-]+\.\w+"
# 手机号(中国)
r"1[3-9]\d{9}"
# URL
r"https?://[\w.-]+"
# 中文
r"[\u4e00-\u9fa5]+"8. 其他常用
# 82. 异常处理
try:
# 可能出错的代码
result = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
except Exception as e:
print(f"其他错误:{e}")
else:
print("没有出错")
finally:
print("无论如何都执行")
# 83. 断言
x = 10
assert x > 0, "x必须大于0"
# 84. 生成器表达式
gen = (x**2 for x in range(10))
# 省内存,逐个生成
# 85. any 和 all
nums = [1, 2, 3, 0]
any(nums) # True(有一个真值)
all(nums) # False(不是全是真值)
# 86. 三元表达式
x = 10
result = "正数" if x > 0 else "非正数"
# 87. 解包
a, b = 1, 2 # 基本解包
a, b = b, a # 交换变量
a, *rest = [1, 2, 3, 4] # a=1, rest=[2,3,4]
# 88. 枚举
for i, val in enumerate(["a", "b", "c"]):
print(i, val)
# 89. 打包
names = ["张三", "李四"]
ages = [18, 19]
for name, age in zip(names, ages):
print(name, age)
# 90. 读取环境变量
import os
os.environ.get("PATH")
os.getenv("HOME")
# 91. 命令行参数
import sys
print(sys.argv) # 命令行参数列表
# 92. 退出程序
import sys
sys.exit()
sys.exit(1) # 错误码
# 93. 打印不换行
print("hello", end=" ")
print("world")
# 94. 打印分隔符
print("a", "b", "c", sep="-") # a-b-c
# 95. 进度条
import time
for i in range(100):
print(f"\r进度:{i+1}%", end="")
time.sleep(0.01)
print()
# 96. 深拷贝
import copy
lst = [[1, 2], [3, 4]]
lst2 = copy.deepcopy(lst)
# 97. 类型判断
isinstance(x, int)
isinstance(x, (int, float))
# 98. 获取对象所有属性
dir(x)
# 99. 查看帮助
help(str)
help(str.split)
# 100. 代码计时
import time
start = time.time()
# 你的代码
end = time.time()
print(f"耗时:{end - start:.4f}秒")9. 进阶技巧
# 101. 装饰器模板
import functools
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# 函数执行前
result = func(*args, **kwargs)
# 函数执行后
return result
return wrapper
# 102. 上下文管理器
with open("file.txt", "r") as f:
content = f.read()
# 自动关闭文件
# 103. 列表去重保持顺序
items = [1, 2, 2, 3, 1]
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
# 104. 扁平化嵌套列表
def flatten(lst):
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
# 105. 记忆化(缓存)
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)🔗 相关章节
📝 我的笔记
在这里添加你自己的常用代码片段
# 你的常用代码
✅ 本章检查清单
- 浏览过所有代码片段
- 知道在哪里查找常用代码
- 掌握最常用的20个代码片段
- 会根据需要查阅对应分类的代码