跳到主要内容
30 个实用的 Python 编程技巧与最佳实践 | 极客日志
Python AI 算法
30 个实用的 Python 编程技巧与最佳实践 综述由AI生成 30 个实用的 Python 编程技巧,涵盖列表推导、枚举、多值返回、链式比较、字符串转换、For-Else 结构、堆操作、字典合并、集合运算及常用内置函数等核心知识点。内容经过清洗去除了无关推广信息,修正了原有代码逻辑错误与拼写错误,并补充了必要的上下文说明与最佳实践建议,旨在帮助开发者提升编码效率与代码质量。
开源信徒 发布于 2025/2/6 更新于 2026/6/1 16 浏览30 个实用的 Python 编程技巧与最佳实践
Python 以其简洁的语法和强大的生态系统著称,掌握一些核心技巧可以显著提升开发效率。本文将详细介绍 30 个常用的 Python 操作技巧,涵盖列表、字典、字符串处理及常用模块的使用。
1. 列表推导式 (List Comprehension)
列表推导式允许在一行代码中方便地循环并创建新列表。
numbers = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
even_numbers = [number for number in numbers if number % 2 == 0 ]
print (even_numbers)
输出:[2, 4, 6, 8]
列表推导式同样适用于字典:
dictionary = {'first_num' : 1 , 'second_num' : 2 ,
'third_num' : 3 , 'fourth_num' : 4 }
odd_values = {key: value for key, value in dictionary.items() if value % 2 != 0 }
print (odd_values)
输出:{'first_num': 1, 'third_num': 3}
2. 枚举函数 (enumerate)
enumerate 函数用于迭代对象(如列表、元组),生成包含索引和值的元组。这在需要同时获取索引和元素时非常有用。
sentence = 'Just do It'
for index, element in enumerate (sentence):
print (f'{index} : {element} ' )
if index == :
( )
index == (sentence) - :
( )
0
print
'The first element!'
elif
len
1
print
'The last element!'
3. 函数返回多个值 在 Python 中,函数可以通过多种方式返回多个值。
方法一:返回元组 def get_student (id_num ):
if id_num == 0 :
return 'Taha' , 'Nate'
elif id_num == 1 :
return 'Jakub' , 'Abdal'
else :
raise Exception(f'No Student with this id: {id_num} ' )
student = get_student(0 )
print (f'First name: {student[0 ]} , Last name: {student[1 ]} ' )
方法二:返回字典 返回字典可以让返回值更具可读性,因为键名提供了语义信息。
def get_data (id_num ):
if id_num == 0 :
return {
'first_name' : 'Muhammad' ,
'last_name' : 'Taha' ,
'title' : 'Data Scientist' ,
'department' : 'A' ,
'date_joined' : '2020-08-07'
}
elif id_num == 1 :
return {
'first_name' : 'Ryan' ,
'last_name' : 'Gosling' ,
'title' : 'Data Engineer' ,
'department' : 'B' ,
'date_joined' : '2020-08-09'
}
else :
raise Exception(f'No employee with this id: {id_num} ' )
employee = get_data(0 )
print (f"Name: {employee['first_name' ]} {employee['last_name' ]} , Title: {employee['title' ]} " )
4. 链式比较运算符 Python 支持数学中的链式比较,例如 1 < x < 30。
5. 字符串转换为列表 使用 ast.literal_eval 可以将格式正确的字符串安全地转换为 Python 数据结构。
import ast
def string_to_list (string ):
return ast.literal_eval(string)
string = "[[1, 2, 3], [4, 5, 6]]"
my_list = string_to_list(string)
print (my_list)
6. For...Else 语句 Python 的 for 循环可以搭配 else 子句。当循环正常结束(未遇到 break)时执行 else 块。
number_list = [1 , 3 , 8 , 9 , 1 ]
for number in number_list:
if number % 2 == 0 :
print (number)
break
else :
print ("No even numbers found!" )
7. 查找列表中最大或最小的 N 个元素 使用 heapq 模块可以高效地查找列表中的极值。
import heapq
numbers = [80 , 25 , 68 , 77 , 95 , 88 , 30 , 55 , 40 , 50 ]
print (heapq.nlargest(5 , numbers))
print (heapq.nsmallest(5 , numbers))
8. 字符串重复 value = "Taha"
print (value * 5 )
print ("-" * 21 )
9. 查找元素的索引 使用 list.index() 方法查找元素首次出现的索引位置。
cities = ['Vienna' , 'Amsterdam' , 'Paris' , 'Berlin' ]
print (cities.index('Berlin' ))
10. 控制打印输出格式 通过 end 和 sep 参数可以灵活控制 print 的输出行为。
print ("Analytics" , end="" )
print ("Vidhya" )
print ("Analytics" , end=" " )
print ("Vidhya" )
print ('Data' , 'science' , 'blogathon' , '12' , sep=', ' )
11. 数字格式化阅读 Python 3.6+ 支持在整数中使用下划线分隔符,提高大数字的可读性。
print (5_000_000_000_000 )
print (7_543_291_635 )
12. 切片反转 sentence = "Data science blogathon"
print (sentence[21 :0 :-1 ])
13. is 与 == 的区别 == 比较值是否相等,is 比较内存地址是否相同。
list1 = [7 , 9 , 4 ]
list2 = [7 , 9 , 4 ]
print (list1 == list2)
print (list1 is list2)
list3 = list1
print (list3 is list1)
14. 合并两个字典 first_dct = {"London" : 1 , "Paris" : 2 }
second_dct = {"Tokyo" : 3 , "Seoul" : 4 }
merged = {**first_dct, **second_dct}
print (merged)
15. 检查字符串前缀 使用 startswith() 方法判断字符串是否以特定字符开头。
sentence = "Analytics Vidhya"
print (sentence.startswith("b" ))
print (sentence.startswith("A" ))
16. 获取字符 Unicode 码点 使用 ord() 函数获取字符对应的 Unicode 整数值。
print (ord ("T" ))
print (ord ("A" ))
print (ord ("h" ))
17. 遍历字典键值对 使用 items() 方法可以同时遍历字典的键和值。
cities = {'London' : 1 , 'Paris' : 2 , 'Tokyo' : 3 , 'Seoul' : 4 }
for key, value in cities.items():
print (f"Key: {key} and Value: {value} " )
18. 在列表指定位置添加值 append() 添加到末尾,insert() 插入到指定索引。
cities = ["London" , "Vienna" , "Rome" ]
cities.append("Seoul" )
print ("After append:" , cities)
cities.insert(0 , "Berlin" )
print ("After insert:" , cities)
19. Filter 函数 filter() 函数根据条件过滤可迭代对象,返回迭代器。
mixed_number = [8 , 15 , 25 , 30 , 34 , 67 , 90 , 5 , 12 ]
filtered_value = filter (lambda x: x > 20 , mixed_number)
print (f"Before filter: {mixed_number} " )
print (f"After filter: {list (filtered_value)} " )
20. 不定长参数函数 def multiplication (*arguments ):
mul = 1
for i in arguments:
mul = mul * i
return mul
print (multiplication(3 , 4 , 5 ))
print (multiplication(5 , 8 , 10 , 3 ))
21. 并行迭代多个列表 capital = ['Vienna' , 'Paris' , 'Seoul' , 'Rome' ]
countries = ['Austria' , 'France' , 'South Korea' , 'Italy' ]
for cap, country in zip (capital, countries):
print (f"{cap} is the capital of {country} " )
22. 检查对象内存大小 使用 sys.getsizeof() 可以查看对象占用的内存字节数。
import sys
mul = 5 * 6
print (sys.getsizeof(mul))
23. Map 函数 values_list = [8 , 10 , 6 , 50 ]
quotient = map (lambda x: x / 2 , values_list)
print (f"Before division: {values_list} " )
print (f"After division: {list (quotient)} " )
24. 统计元素出现次数 列表的 count() 方法用于统计某元素出现的次数。
cities = ["Amsterdam" , "Berlin" , "New York" , "Seoul" , "Tokyo" , "Paris" , "Paris" , "Vienna" , "Paris" ]
print (f"Paris appears {cities.count('Paris' )} times in the list" )
25. 元组或列表查找索引 cities_tuple = ("Berlin" , "Paris" , 5 , "Vienna" , 10 )
print (cities_tuple.index("Paris" ))
cities_list = ['Vienna' , 'Paris' , 'Seoul' , 'Amsterdam' ]
print (cities_list.index('Amsterdam' ))
26. 集合交集与并集 set1 = {'Vienna' , 'Paris' , 'Seoul' }
set2 = {"Tokyo" , "Rome" , 'Amsterdam' }
print (set1.union(set2))
27. 按频率排序 使用 collections.Counter 可以轻松统计频率并排序。
from collections import Counter
count = Counter([7 , 6 , 5 , 6 , 8 , 6 , 6 , 6 ])
print (count)
print ("Sort values according their frequency:" , count.most_common())
28. 去除列表重复值 cities_list = ['Vienna' , 'Paris' , 'Seoul' , 'Amsterdam' , 'Paris' , 'Amsterdam' , 'Paris' ]
cities_list = list (set (cities_list))
print ("After removing duplicates:" , cities_list)
29. 找出两个列表的差异 使用集合的对称差集 symmetric_difference 找出差异元素。
cities_list1 = ['Vienna' , 'Paris' , 'Seoul' , 'Amsterdam' , 'Berlin' , 'London' ]
cities_list2 = ['Vienna' , 'Paris' , 'Seoul' , 'Amsterdam' ]
cities_set1 = set (cities_list1)
cities_set2 = set (cities_list2)
difference = list (cities_set1.symmetric_difference(cities_set2))
print (difference)
30. 列表转字典 使用 zip() 和 dict() 将两个列表转换为字典。
number = [1 , 2 , 3 ]
cities = ['Vienna' , 'Paris' , 'Seoul' ]
result = dict (zip (number, cities))
print (result)
总结 以上 30 个技巧涵盖了 Python 日常开发中的高频场景。熟练掌握这些基础操作不仅能提升代码简洁度,还能增强程序的可读性和性能。建议在实际项目中多加练习,结合官方文档深入理解每个函数的底层机制。持续学习新的语言特性(如 f-string、类型提示等)也是保持竞争力的关键。
相关免费在线工具 加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
随机西班牙地址生成器 随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
Gemini 图片去水印 基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
curl 转代码 解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online