30 个极简 Python 代码片段与实用技巧
Python 因其简洁易读的语法和强大的生态系统,成为数据科学、自动化脚本及 Web 开发的首选语言。掌握一些核心技巧和标准库用法,能显著提升编码效率。以下整理了 30 个实用的 Python 代码片段,涵盖列表操作、字符串处理、字典管理及性能优化等方面。每个片段均附带简要原理说明,帮助开发者快速理解并应用到实际项目中。
本文整理了 30 个 Python 实用代码片段,涵盖列表去重、字符串处理、字典合并、性能测试等核心技巧。内容包含具体代码示例与原理说明,旨在帮助开发者提升编码效率。通过掌握集合运算、生成器、正则匹配及标准库函数,可解决日常开发中的常见问题。适合初学者巩固基础及进阶开发者优化代码风格。

Python 因其简洁易读的语法和强大的生态系统,成为数据科学、自动化脚本及 Web 开发的首选语言。掌握一些核心技巧和标准库用法,能显著提升编码效率。以下整理了 30 个实用的 Python 代码片段,涵盖列表操作、字符串处理、字典管理及性能优化等方面。每个片段均附带简要原理说明,帮助开发者快速理解并应用到实际项目中。
检查列表中是否存在重复元素是常见需求。利用集合(Set)的唯一性特性,可以快速判断。
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6]
y = [1, 2, 3, 4, 5]
print(all_unique(x)) # False
print(all_unique(y)) # True
原理: set() 会去除重复项,比较原列表长度与集合长度即可判断。时间复杂度为 O(n)。
判断两个字符串是否由相同的字符组成(变位词)。使用 collections.Counter 统计字符频率。
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
print(anagram("abcd3", "3acdb")) # True
原理: Counter 返回字符计数字典,直接比较字典相等性。
查看变量在内存中占用的字节数,有助于进行内存优化分析。
import sys
variable = 30
print(sys.getsizeof(variable)) # 24
注意: getsizeof 仅返回对象本身的大小,不包含引用的其他对象大小。
计算字符串编码后的字节数,常用于网络传输或存储限制场景。
def byte_size(string):
return len(string.encode('utf-8'))
print(byte_size(':grinning:')) # 4
print(byte_size('Hello World')) # 11
原理: 不同字符在 UTF-8 编码下占用字节数不同(如 Emoji 可能占多字节)。
利用字符串乘法运算符,无需循环即可重复输出字符串。
n = 2
s = "Programming"
print(s * n) # ProgrammingProgramming
优势: 比 for 循环更简洁,底层由 C 实现,效率较高。
将字符串中每个单词的首字母大写。
s = "programming is awesome"
print(s.title()) # Programming Is Awesome
适用: 标题格式化。注意 capitalize() 仅大写首字母,其余小写。
将列表按指定大小切分为多个子列表。
from math import ceil
def chunk(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(0, ceil(len(lst) / size)))))
print(chunk([1, 2, 3, 4, 5], 2)) # [[1, 2], [3, 4], [5]]
应用: 分页处理或批量任务分发。
过滤掉列表中的假值(False, None, 0, "" 等)。
def compact(lst):
return list(filter(bool, lst))
print(compact([0, 1, False, 2, '', 3, 'a', 's', 34])) # [1, 2, 3, 'a', 's', 34]
原理: bool() 函数将非零、非空对象转为 True。
将成对的列表转换为元组列表(类似矩阵转置)。
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(list(transposed)) # [('a', 'c', 'e'), ('b', 'd', 'f')]
注意: zip 返回迭代器,需转换为 list 查看。
支持在一个表达式中比较多个值,增强可读性。
a = 3
print(2 < a < 8) # True
print(1 == a < 2) # False
等价于: (2 < a) and (a < 8)。
将列表元素拼接为字符串,自定义分隔符。
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming
技巧: join 方法通常比字符串累加更高效。
统计字符串中元音字母的数量,使用正则表达式。
import re
def count_vowels(str_val):
return len(re.findall(r'[aeiou]', str_val, re.IGNORECASE))
print(count_vowels('foobar')) # 3
print(count_vowels('gym')) # 0
修正: 原文本中 len(len(...)) 有误,已修正为 len(...)。
将字符串首字符统一转换为小写。
def decapitalize(string):
return string[:1].lower() + string[1:]
print(decapitalize('FooBar')) # 'fooBar'
注意: 确保变量名一致,避免引用错误。
将嵌套列表展平为一维列表。
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(lst):
result = []
result.extend(
spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
return result
print(deep_flatten([1, [2], [[3], 4], 5])) # [1, 2, 3, 4, 5]
原理: 递归调用处理深层嵌套结构。
获取存在于第一个列表但不存在于第二个列表的元素。
def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
print(difference([1, 2, 3], [1, 2, 4])) # [3]
优化: 使用集合运算比遍历列表更快。
基于转换后的结果计算差集,适用于复杂对象比较。
def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
from math import floor
print(difference_by([2.1, 1.2], [2.3, 3.4], floor)) # [1.2]
场景: 比较浮点数时忽略小数部分。
根据条件动态选择函数执行。
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9
技巧: 三元运算符结合函数调用,减少嵌套。
检测列表中是否有重复元素(与第 1 点类似)。
def has_duplicates(lst):
return len(lst) != len(set(lst))
x = [1, 2, 3, 4, 5, 5]
y = [1, 2, 3, 4, 5]
print(has_duplicates(x)) # True
print(has_duplicates(y)) # False
合并两个字典对象。
def merge_two_dicts(a, b):
c = a.copy()
c.update(b)
return c
a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}
Python 3.5+ 写法: {**a, **b} 更为简洁。
通过键值对列表构建字典。
def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values)) # {'a': 2, 'b': 3, 'c': 4}
注意: 键值数量需一致,否则多余部分会被丢弃。
遍历列表同时获取索引和值。
items = ["a", "b", "c", "d"]
for index, element in enumerate(items):
print(f"Value {element} Index {index}")
改进: 避免使用内置类型 list 作为变量名。
测量代码片段的运行耗时。
import time
start_time = time.time()
a = 1
b = 2
c = a + b
end_time = time.time()
total_time = end_time - start_time
print(f"Time: {total_time}")
用途: 性能基准测试或调试。
当 try 块无异常时执行 else 块。
try:
2 * 3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")
逻辑: else 仅在无异常抛出时执行,区别于 finally。
找出列表中出现频率最高的元素。
def most_frequent(list_):
return max(set(list_), key=list_.count)
lst = [1, 2, 1, 2, 3, 2, 1, 4, 2]
print(most_frequent(lst)) # 2
注意: 若有多个最高频元素,仅返回第一个。
检查字符串是否为回文(忽略非字母字符)。
def palindrome(string):
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1]
print(palindrome('taco cat')) # True
处理: 移除空格和标点后再比对反转字符串。
通过字典映射运算符实现加减乘除。
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25
扩展: 适合动态计算场景,避免大量条件判断。
打乱列表顺序,使用 Fisher-Yates 算法。
from copy import deepcopy
from random import randint
def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while m:
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst
foo = [1, 2, 3]
print(shuffle(foo)) # 随机顺序
注意: 不修改原列表,返回新列表。
将包含子列表的列表扁平化一层。
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
print(spread([1, 2, 3, [4, 5, 6], [7], 8, 9])) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
区别: 不同于递归深度展开,此法仅处理一级嵌套。
无需临时变量交换两个变量的值。
def swap(a, b):
return b, a
a, b = -1, 14
result = swap(a, b)
print(result) # (14, -1)
机制: Python 元组解包特性。
安全获取字典值并设置默认返回值。
d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3
对比: 若 Key 不存在且未设默认值,d['c'] 会抛出 KeyError。
以上 30 个技巧涵盖了 Python 日常开发中的高频场景。熟练掌握这些基础用法,能够编写出更简洁、高效的代码。建议在实际项目中多加练习,结合官方文档深入理解相关模块。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online