前言
Python 是一种通用的高级编程语言。用它可以做许多事,比如开发桌面 GUI 应用程序、网站和 Web 应用程序等。
作为一种高级编程语言,Python 还可以让你通过处理常见的编程任务来专注应用程序的核心功能。并且,编程语言的简单语法规则进一步简化了代码库的可读性和应用程序的可维护性。
与其他编程语言相比,Python 的优势在于:
- 与主要平台和操作系统兼容;
- 有许多开源框架和工具;
本文整理了 25 个简短且实用的 Python 代码片段,涵盖变量交换、奇偶判断、字符串处理、列表操作、内存检测、文件读写、时间处理及常用库应用等内容。通过精简的代码示例,帮助开发者快速解决日常编程任务,提升代码可读性与开发效率。

Python 是一种通用的高级编程语言。用它可以做许多事,比如开发桌面 GUI 应用程序、网站和 Web 应用程序等。
作为一种高级编程语言,Python 还可以让你通过处理常见的编程任务来专注应用程序的核心功能。并且,编程语言的简单语法规则进一步简化了代码库的可读性和应用程序的可维护性。
与其他编程语言相比,Python 的优势在于:
在本文中,我将介绍 25 个简短且有用的代码段,它们可以帮你完成日常任务。
在其他语言中,要在两个变量间交换值而不是用第三个变量,我们要么使用算术运算符,要么使用位异或(Bitwise XOR)。在 Python 中,它就简单多了,如下所示。
a = 5
b = 10
a, b = b, a
print(a) # 10
print(b) # 5
如果给定的数字为偶数,则如下函数返回 True,否则返回 False。
def is_even(num):
return num % 2 == 0
is_even(10) # True
以下函数可用于将多行字符串拆分为行列表。
def split_lines(s):
return s.split('\n')
split_lines('50\n python\n snippets') # ['50', ' python', ' snippets']
标准库的 sys 模块提供了 getsizeof() 函数。该函数接受一个对象,调用对象的 sizeof() 方法,并返回结果,这样做能使对象可检查。
import sys
print(sys.getsizeof(5)) # 28
print(sys.getsizeof("Python")) # 55
Python 字符串库不像其他 Python 容器(如 list)那样支持内置的 reverse()。反转字符串有很多方法,其中最简单的方法是使用切片运算符(slicing operator)。
language = "python"
reversed_language = language[::-1]
print(reversed_language) # nohtyp
在不使用循环的情况下,要打印一个字符串 n 次是非常容易的,如下所示。
def repeat(string, n):
return (string * n)
repeat('python', 3) # pythonpythonpython
以下函数用于检查字符串是否为回文。
def palindrome(string):
return string == string[::-1]
palindrome('python') # False
下面的代码段将字符串列表组合成单个字符串。
strings = ['50', 'python', 'snippets']
print(','.join(strings)) # 50,python,snippets
此函数返回所传递列表的第一个元素。
def head(lst):
return lst[0]
print(head([1, 2, 3, 4, 5])) # 1
此函数返回两个列表中任一列表中的每个元素。
def union(a, b):
return list(set(a + b))
union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4]) # [1, 2, 3, 4, 5, 6, 8]
此函数返回给定列表中存在的唯一元素。
def unique_elements(numbers):
return list(set(numbers))
unique_elements([1, 2, 3, 2, 4]) # [1, 2, 3, 4]
此函数返回列表中两个或多个数字的平均值。
def average(*args):
return sum(args, 0.0) / len(args)
average(5, 8, 2) # 5.0
此函数检查列表中的所有元素是否都是唯一的。
def unique_check(lst):
if len(lst) == len(set(lst)):
print("All elements are unique")
else:
print("List has duplicates")
unique_check([1, 2, 3, 4, 5]) # All elements are unique
Python 计数器跟踪容器中每个元素的频率。Counter() 返回一个以元素为键、以其出现频率为值的字典。
from collections import Counter
lst = [1, 2, 3, 2, 4, 3, 2, 3]
count = Counter(lst)
print(count) # {2: 3, 3: 3, 1: 1, 4: 1}
此函数返回列表中出现频率最高的元素。
def most_frequent(lst):
return max(set(lst), key=lst.count)
numbers = [1, 2, 3, 2, 4, 3, 1, 3]
most_frequent(numbers) # 3
使用 datetime 模块可以轻松获取当前的日期和时间。
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
可以使用递归或迭代将嵌套列表展平为一维列表。
def flatten(nested_list):
result = []
for item in nested_list:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
flatten([1, [2, 3], [4, [5, 6]]]) # [1, 2, 3, 4, 5, 6]
Python 3.5+ 支持使用 ** 操作符合并字典。
d1 = {'a': 1}
d2 = {'b': 2}
d3 = {**d1, **d2}
print(d3) # {'a': 1, 'b': 2}
利用 dict 的特性(Python 3.7+ 保持插入顺序)进行去重。
def dedup_preserve_order(lst):
return list(dict.fromkeys(lst))
dedup_preserve_order([1, 2, 2, 3, 1]) # [1, 2, 3]
使用 os.path 模块可以方便地检查文件路径。
import os
if os.path.exists('example.txt'):
print("File exists")
else:
print("File not found")
使用 with 语句安全地打开并读取文件。
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
结合 random 和 string 模块生成强密码。
import random
import string
password = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(12))
print(password)
在实际开发中,防抖常用于优化高频事件处理。
import time
def debounce(wait_time):
def decorator(func):
last_call = [None]
def wrapper(*args, **kwargs):
now = time.time()
if now - last_call[0] >= wait_time:
last_call[0] = now
func(*args, **kwargs)
return wrapper
return decorator
defaultdict 可以自动初始化不存在的键。
from collections import defaultdict
d = defaultdict(int)
d['a'] += 1
print(d['a']) # 1
print(d['b']) # 0
f-string 是 Python 3.6+ 引入的高效字符串格式化方式。
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
# Name: Alice, Age: 30
以上 25 个代码片段涵盖了 Python 编程中常见的基础操作,希望能为你的日常开发提供便利。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online