哪些Python案例展示了列表推导式?

wen python案例 6

本文目录导读:

哪些Python案例展示了列表推导式?

  1. 基础变换:对每个元素进行操作
  2. 条件过滤:保留满足条件的元素
  3. 条件赋值:应用三元表达式
  4. 嵌套循环:处理多重迭代
  5. 实用数据处理场景
  6. 组合:过滤 + 变换
  7. 使用 enumerate 获取索引

Python 列表推导式(List Comprehension)是一种简洁、高效创建列表的方式,下面我按 实用场景 分类,展示几个经典案例。


基础变换:对每个元素进行操作

案例:将列表中的数字平方

# 传统 for 循环
nums = [1, 2, 3, 4, 5]
squares = []
for n in nums:
    squares.append(n ** 2)
# 列表推导式
squares = [n ** 2 for n in nums]
print(squares)  # [1, 4, 9, 16, 25]

案例:字符串转大写

words = ['hello', 'world', 'python']
upper_words = [w.upper() for w in words]
print(upper_words)  # ['HELLO', 'WORLD', 'PYTHON']

条件过滤:保留满足条件的元素

案例:筛选出偶数

nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
print(evens)  # [2, 4, 6]

案例:筛选出长度大于 3 的单词

words = ['cat', 'dog', 'elephant', 'bird']
long_words = [w for w in words if len(w) > 3]
print(long_words)  # ['elephant', 'bird']

条件赋值:应用三元表达式

案例:奇偶数标记

nums = [1, 2, 3, 4, 5]
labels = ['even' if n % 2 == 0 else 'odd' for n in nums]
print(labels)  # ['odd', 'even', 'odd', 'even', 'odd']

案例:数值归一化(正数直接保留,负数变 0)

nums = [10, -5, 8, -3, 0]
clamped = [n if n > 0 else 0 for n in nums]
print(clamped)  # [10, 0, 8, 0, 0]

嵌套循环:处理多重迭代

案例:生成乘法表(2层循环)

# 生成 1到3 的乘法表
table = [f"{i}x{j}={i*j}" for i in range(1, 4) for j in range(1, 4)]
print(table)
# ['1x1=1', '1x2=2', '1x3=3', '2x1=2', '2x2=4', '2x3=6', '3x1=3', '3x2=6', '3x3=9']

案例:矩阵扁平化(二维转一维)

matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6]

实用数据处理场景

案例:去除字符串中的空白字符

text = "  apple  , banana , cherry "
clean = [item.strip() for item in text.split(',')]
print(clean)  # ['apple', 'banana', 'cherry']

案例:从字典中提取特定值

students = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
passed_names = [name for name, score in students.items() if score >= 80]
print(passed_names)  # ['Alice', 'Bob']

案例:读取文件并去除空行

# 假设文件 data.txt 内容为:
# line1
#
# line2
# line3
with open('data.txt') as f:
    lines = [line.strip() for line in f if line.strip()]
print(lines)  # ['line1', 'line2', 'line3']

组合:过滤 + 变换

案例:对偶数取平方

nums = [1, 2, 3, 4, 5, 6]
result = [n ** 2 for n in nums if n % 2 == 0]
print(result)  # [4, 16, 36]

案例:找出所有 3 的倍数并转为字符串

nums = range(10)
result = [str(n) for n in nums if n % 3 == 0]
print(result)  # ['0', '3', '6', '9']

使用 enumerate 获取索引

案例:带索引的转换

words = ['apple', 'banana', 'cherry']
indexed = [f"{i}:{w}" for i, w in enumerate(words)]
print(indexed)  # ['0:apple', '1:banana', '2:cherry']

场景 典型写法
基本变换 [f(x) for x in iterable]
条件过滤 [x for x in iterable if condition]
条件赋值(三元) [a if cond else b for x in iterable]
嵌套循环 [f(x, y) for x in X for y in Y]
过滤 + 变换 [f(x) for x in iterable if condition]
与字典/枚举结合 [f(k, v) for k, v in dict.items()]

需要注意的是:列表推导式虽然简洁,但 不要过度嵌套(超过 2 层),否则会严重影响可读性。

抱歉,评论功能暂时关闭!