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

