30 个实用的 Python 编程技巧与最佳实践
Python 以其简洁的语法和强大的生态系统著称,掌握一些核心技巧可以显著提升开发效率。本文将详细介绍 30 个常用的 Python 操作技巧,涵盖列表、字典、字符串处理及常用模块的使用。
本文详细介绍了 30 个实用的 Python 编程技巧,涵盖列表推导、枚举、多值返回、链式比较、字符串转换、For-Else 结构、堆操作、字典合并、集合运算及常用内置函数等核心知识点。内容经过清洗去除了无关推广信息,修正了原有代码逻辑错误与拼写错误,并补充了必要的上下文说明与最佳实践建议,旨在帮助开发者提升编码效率与代码质量。

Python 以其简洁的语法和强大的生态系统著称,掌握一些核心技巧可以显著提升开发效率。本文将详细介绍 30 个常用的 Python 操作技巧,涵盖列表、字典、字符串处理及常用模块的使用。
列表推导式允许在一行代码中方便地循环并创建新列表。
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}
enumerate 函数用于迭代对象(如列表、元组),生成包含索引和值的元组。这在需要同时获取索引和元素时非常有用。
sentence = 'Just do It'
for index, element in enumerate(sentence):
print(f'{index}: {element}')
if index == 0:
print('The first element!')
elif index == len(sentence) - 1:
print('The last element!')
在 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']}")
Python 支持数学中的链式比较,例如 1 < x < 30。
x = 5
print(1 < x < 30) # 输出 True
# 等价于 (1 < x) and (x < 30)
使用 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)
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!")
使用 heapq 模块可以高效地查找列表中的极值。
import heapq
numbers = [80, 25, 68, 77, 95, 88, 30, 55, 40, 50]
print(heapq.nlargest(5, numbers)) # 最大的 5 个
print(heapq.nsmallest(5, numbers)) # 最小的 5 个
使用乘法运算符可以直接重复字符串。
value = "Taha"
print(value * 5) # Tahahaha...
print("-" * 21) # ---------------------
使用 list.index() 方法查找元素首次出现的索引位置。
cities = ['Vienna', 'Amsterdam', 'Paris', 'Berlin']
print(cities.index('Berlin')) # 输出 3
通过 end 和 sep 参数可以灵活控制 print 的输出行为。
print("Analytics", end="")
print("Vidhya")
print("Analytics", end=" ")
print("Vidhya")
print('Data', 'science', 'blogathon', '12', sep=', ') # Data, science, blogathon, 12
Python 3.6+ 支持在整数中使用下划线分隔符,提高大数字的可读性。
print(5_000_000_000_000)
print(7_543_291_635)
通过设置负步长,可以在切片时反转顺序。
sentence = "Data science blogathon"
print(sentence[21:0:-1]) # 从倒数第二个字符开始向前取到索引 1
is 与 == 的区别== 比较值是否相等,is 比较内存地址是否相同。
list1 = [7, 9, 4]
list2 = [7, 9, 4]
print(list1 == list2) # True (值相等)
print(list1 is list2) # False (不同对象)
list3 = list1
print(list3 is list1) # True (同一对象)
使用解包运算符 ** 可以合并字典。
first_dct = {"London": 1, "Paris": 2}
second_dct = {"Tokyo": 3, "Seoul": 4}
merged = {**first_dct, **second_dct}
print(merged)
使用 startswith() 方法判断字符串是否以特定字符开头。
sentence = "Analytics Vidhya"
print(sentence.startswith("b")) # False
print(sentence.startswith("A")) # True
使用 ord() 函数获取字符对应的 Unicode 整数值。
print(ord("T"))
print(ord("A"))
print(ord("h"))
使用 items() 方法可以同时遍历字典的键和值。
cities = {'London': 1, 'Paris': 2, 'Tokyo': 3, 'Seoul': 4}
for key, value in cities.items():
print(f"Key: {key} and Value: {value}")
append() 添加到末尾,insert() 插入到指定索引。
cities = ["London", "Vienna", "Rome"]
cities.append("Seoul")
print("After append:", cities)
cities.insert(0, "Berlin")
print("After insert:", cities)
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)}")
使用 *args 可以接收任意数量的位置参数。
def multiplication(*arguments):
mul = 1
for i in arguments:
mul = mul * i
return mul
print(multiplication(3, 4, 5)) # 60
print(multiplication(5, 8, 10, 3)) # 1200
使用 zip() 函数可以同时迭代多个列表。
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}")
使用 sys.getsizeof() 可以查看对象占用的内存字节数。
import sys
mul = 5 * 6
print(sys.getsizeof(mul))
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)}")
列表的 count() 方法用于统计某元素出现的次数。
cities = ["Amsterdam", "Berlin", "New York", "Seoul", "Tokyo", "Paris", "Paris", "Vienna", "Paris"]
print(f"Paris appears {cities.count('Paris')} times in the list")
元组和列表都支持 index() 方法。
cities_tuple = ("Berlin", "Paris", 5, "Vienna", 10)
print(cities_tuple.index("Paris"))
cities_list = ['Vienna', 'Paris', 'Seoul', 'Amsterdam']
print(cities_list.index('Amsterdam'))
使用 union() 或 | 运算符合并集合。
set1 = {'Vienna', 'Paris', 'Seoul'}
set2 = {"Tokyo", "Rome", 'Amsterdam'}
print(set1.union(set2))
使用 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())
利用集合的唯一性去除列表中的重复项。
cities_list = ['Vienna', 'Paris', 'Seoul', 'Amsterdam', 'Paris', 'Amsterdam', 'Paris']
cities_list = list(set(cities_list))
print("After removing duplicates:", cities_list)
使用集合的对称差集 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)
使用 zip() 和 dict() 将两个列表转换为字典。
number = [1, 2, 3]
cities = ['Vienna', 'Paris', 'Seoul']
result = dict(zip(number, cities))
print(result)
以上 30 个技巧涵盖了 Python 日常开发中的高频场景。熟练掌握这些基础操作不仅能提升代码简洁度,还能增强程序的可读性和性能。建议在实际项目中多加练习,结合官方文档深入理解每个函数的底层机制。持续学习新的语言特性(如 f-string、类型提示等)也是保持竞争力的关键。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 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