本文目录导读:

我来详细讲解Python推导式语法的使用案例,包括列表、字典、集合等多种类型。
列表推导式
基础示例
# 生成1-10的平方
squares = [x**2 for x in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 转换字符串列表
words = ['hello', 'world', 'python']
upper_words = [word.upper() for word in words]
print(upper_words) # ['HELLO', 'WORLD', 'PYTHON']
# 处理数据文件
prices = ['$12.5', '$8.99', '$15.0', '$20.5']
clean_prices = [float(p.replace('$', '')) for p in prices]
print(clean_prices) # [12.5, 8.99, 15.0, 20.5]
带条件的列表推导式
# 筛选偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# 筛选学生成绩
scores = [85, 92, 78, 95, 60, 88, 73]
passed = [score for score in scores if score >= 80]
print(passed) # [85, 92, 95, 88]
# 条件过滤-筛选文件名
files = ['data.txt', 'image.jpg', 'doc.pdf', 'notes.txt', 'photo.png']
txt_files = [f for f in files if f.endswith('.txt')]
print(txt_files) # ['data.txt', 'notes.txt']
嵌套循环的列表推导式
# 生成乘法表(1-5)
multiplication = [f"{i}x{j}={i*j}" for i in range(2, 6) for j in range(1, 10)]
print(multiplication[:5]) # ['2x1=2', '2x2=4', '2x3=6', '2x4=8', '2x5=10']
# 矩阵转置
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# 生成坐标对
coordinates = [(x, y) for x in range(3) for y in range(3)]
print(coordinates) # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
字典推导式
基础示例
# 创建数字平方字典
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 交换键值
original = {'a': 1, 'b': 2, 'c': 3}
swapped = {value: key for key, value in original.items()}
print(swapped) # {1: 'a', 2: 'b', 3: 'c'}
# 转换数据类型
data = {'name': 'alice', 'age': '25', 'score': '95'}
converted = {k: int(v) if v.isdigit() else v for k, v in data.items()}
print(converted) # {'name': 'alice', 'age': 25, 'score': 95}
实际应用案例
# 统计字符出现次数
text = "hello world"
char_count = {char: text.count(char) for char in set(text) if char != ' '}
print(char_count) # {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}
# 筛选字典元素
students = {
'Alice': 85,
'Bob': 92,
'Charlie': 78,
'David': 95,
'Eve': 88
}
excellent = {name: score for name, score in students.items() if score >= 90}
print(excellent) # {'Bob': 92, 'David': 95}
# 列表转换字典
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
student_dict = {names[i]: scores[i] for i in range(len(names))}
print(student_dict) # {'Alice': 85, 'Bob': 92, 'Charlie': 78}
集合推导式
基础示例
# 去重并转换类型
numbers = [1, 2, 2, 3, 3, 3, 4, 5, 5, 6, 6, 7]
unique_squares = {n**2 for n in numbers}
print(unique_squares) # {1, 4, 9, 16, 25, 36, 49}
# 提取单词首字母
phrases = ["Hello World", "Python Programming", "Data Science"]
first_chars = {phrase[0] for phrase in phrases}
print(first_chars) # {'H', 'D', 'P'}
# 筛选特定条件
numbers_set = {x for x in range(50) if x % 5 == 0 and x % 3 == 0}
print(numbers_set) # {0, 15, 30, 45}
生成器推导式
基础示例
# 创建生成器
large_gen = (x**2 for x in range(1000000))
print(next(large_gen)) # 0
print(next(large_gen)) # 1
print(next(large_gen)) # 4
# 节省内存处理大数据
def process_large_data():
# 传统方式会占用大量内存
# large_list = [x for x in range(100000000)]
# 使用生成器节省内存
large_gen = (x for x in range(100000000))
return sum(large_gen)
# 分批处理数据
chunks = (sum(i for i in range(start, start+1000))
for start in range(0, 10000, 1000))
for chunk_sum in chunks:
print(chunk_sum, end=' ') # 输出每批的和
多条件组合
复杂条件筛选
# 筛选质数与完全平方数
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
# 找出既是质数又是回文的数(100-1000)
special_numbers = [n for n in range(100, 1000)
if is_prime(n) and str(n) == str(n)[::-1]]
print(special_numbers) # [101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929]
# 多层条件过滤
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
complex_filter = [x for x in data
if x > 5
and x % 3 == 0
and str(x).startswith('1')]
print(complex_filter) # [12, 15]
实际项目案例
数据处理
# 解析CSV数据
csv_data = """name,age,score
Alice,25,85
Bob,30,92
Charlie,22,78"""
lines = csv_data.strip().split('\n')
headers = lines[0].split(',')
records = [dict(zip(headers, line.split(','))) for line in lines[1:]]
print(records) # [{'name': 'Alice', 'age': '25', 'score': '85'}, ...]
# 根据条件转换
processed = [{'name': r['name'],
'age': int(r['age']),
'score': float(r['score']),
'grade': 'A' if float(r['score']) >= 90 else 'B' if float(r['score']) >= 80 else 'C'}
for r in records]
print(processed)
文件处理
import os
# 批量重命名文件
files = [f"file_{i}.txt" for i in range(1, 6)]
# 模拟文件列表
files_to_rename = ['report1.pdf', 'report2.pdf', 'report3.pdf', 'image1.jpg']
# 创建新文件名
renamed = [f"2023_{f}" for f in files_to_rename if f.endswith('.pdf')]
print(renamed) # ['2023_report1.pdf', '2023_report2.pdf', '2023_report3.pdf']
# 提取文件扩展名
extensions = {os.path.splitext(f)[1] for f in files_to_rename}
print(extensions) # {'.pdf', '.jpg'}
性能对比
import time
# 传统循环 vs 推导式
def traditional_loop(n):
result = []
for i in range(n):
if i % 2 == 0:
result.append(i ** 2)
return result
def list_comprehension(n):
return [i ** 2 for i in range(n) if i % 2 == 0]
# 测试性能
n = 1000000
start = time.time()
result1 = traditional_loop(n)
print(f"传统循环: {time.time() - start:.4f}秒")
start = time.time()
result2 = list_comprehension(n)
print(f"列表推导式: {time.time() - start:.4f}秒")
# 推导式通常快2-3倍
高级技巧
条件表达式(三元运算符)
# 复杂条件判断 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] classified = ['Even' if n % 2 == 0 else 'Odd' for n in numbers] print(classified) # ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even'] # 多维条件 grades = [n if n >= 60 else 'Failed' for n in [45, 78, 92, 55, 88]] print(grades) # ['Failed', 78, 92, 'Failed', 88]
嵌套推导式
# 创建三维坐标
points_3d = [(x, y, z) for x in range(3) for y in range(3) for z in range(3)]
print(len(points_3d)) # 27个点
# 矩阵运算
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
# 矩阵乘法
result = [[sum(A[i][k] * B[k][j] for k in range(2))
for j in range(2)]
for i in range(2)]
print(result) # [[19, 22], [43, 50]]
最佳实践建议
- 可读性优先:如果推导式过于复杂(超过2层条件或循环),考虑使用普通循环
- 性能考虑:处理大量数据时优先使用生成器表达式
- 调试方便:复杂逻辑可以先写成普通循环,调试成功后再改为推导式
- 避免副作用:推导式主要用于生成新数据,不要在其中进行打印等操作
注意事项
# ❌ 避免这种复杂的推导式 complex_comp = [x for x in [y for y in [z for z in range(10) if z > 5] if y < 8] if x > 6] # ✅ 改写为更清晰的版本 step1 = [z for z in range(10) if z > 5] step2 = [y for y in step1 if y < 8] result = [x for x in step2 if x > 6] print(result) # [7]
掌握推导式语法能让你的Python代码更简洁、高效,建议从简单的例子开始,逐步应用到实际项目中。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播