Python案例怎么用列表推导式取值?

wen python案例 11

本文目录导读:

Python案例怎么用列表推导式取值?

  1. 基础列表推导式取值
  2. 带条件筛选的列表推导式
  3. 嵌套列表推导式
  4. 带索引的列表推导式
  5. 实用的案例分析
  6. 性能优化技巧
  7. 练习题

我来详细讲解Python中列表推导式的各种取值方法。

基础列表推导式取值

# 基本语法:[表达式 for 变量 in 可迭代对象]
# 示例1:从列表中获取每个元素
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers]
print(squared)  # [1, 4, 9, 16, 25]
# 示例2:字符串列表
fruits = ['apple', 'banana', 'cherry']
upper_fruits = [fruit.upper() for fruit in fruits]
print(upper_fruits)  # ['APPLE', 'BANANA', 'CHERRY']

带条件筛选的列表推导式

# 语法:[表达式 for 变量 in 可迭代对象 if 条件]
# 示例1:筛选偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)  # [2, 4, 6, 8]
# 示例2:筛选长度大于3的字符串
words = ['hi', 'hello', 'world', 'python', 'to']
long_words = [w.upper() for w in words if len(w) > 3]
print(long_words)  # ['HELLO', 'WORLD', 'PYTHON']
# 示例3:多个条件
numbers = range(1, 20)
specific = [x for x in numbers if x > 5 and x < 15]
print(specific)  # [6, 7, 8, 9, 10, 11, 12, 13, 14]

嵌套列表推导式

# 处理二维列表
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 示例1:展平二维列表
flat = [item for row in matrix for item in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 示例2:从嵌套结构中取值
students = [
    {'name': '张三', 'scores': [85, 90, 78]},
    {'name': '李四', 'scores': [92, 88, 95]},
    {'name': '王五', 'scores': [70, 80, 85]}
]
# 获取所有学生姓名
names = [s['name'] for s in students]
print(names)  # ['张三', '李四', '王五']
# 获取所有分数
all_scores = [score for s in students for score in s['scores']]
print(all_scores)  # [85, 90, 78, 92, 88, 95, 70, 80, 85]

带索引的列表推导式

# 使用enumerate获取索引
fruits = ['apple', 'banana', 'orange', 'grape']
# 示例1:获取索引和值
indexed = [(i, fruit) for i, fruit in enumerate(fruits)]
print(indexed)  # [(0, 'apple'), (1, 'banana'), (2, 'orange'), (3, 'grape')]
# 示例2:根据索引进行筛选
even_indexed = [fruit for i, fruit in enumerate(fruits) if i % 2 == 0]
print(even_indexed)  # ['apple', 'orange']

实用的案例分析

案例1:数据清洗

# 处理用户输入数据
raw_data = ['  hello  ', 'World', '', '  PYTHON  ', '   ', 'data']
# 清洗:去除空白、转为小写、过滤空字符串
cleaned = [item.strip().lower() 
           for item in raw_data 
           if item.strip()]
print(cleaned)  # ['hello', 'world', 'python', 'data']

案例2:文件处理

# 假设有一个文件内容
lines = [
    'Name: Zhang San',
    'Age: 25',
    '# This is a comment',
    'Score: 85',
    '',
    'Name: Li Si',
    'Score: 92'
]
# 提取所有数值
import re
values = [line.split(': ')[1] 
          for line in lines 
          if ':' in line and not line.startswith('#')]
print(values)  # ['Zhang San', '25', '85', 'Li Si', '92']
# 只提取数字
numbers = [int(line.split(': ')[1]) 
           for line in lines 
           if line.startswith(('Age', 'Score'))]
print(numbers)  # [25, 85, 92]

案例3:数据转换和映射

# 温度转换
celsius = [0, 10, 20, 30, 40]
fahrenheit = [(c * 9/5) + 32 for c in celsius]
print(fahrenheit)  # [32.0, 50.0, 68.0, 86.0, 104.0]
# 字典键值对转换
student_scores = {'张三': 85, '李四': 92, '王五': 78}
# 获取高分学生
high_scorers = [name for name, score in student_scores.items() if score >= 80]
print(high_scorers)  # ['张三', '李四']

案例4:条件替换

# 列表元素替换
numbers = [1, 2, 3, 4, 5, 6]
# 大于3的替换为"大",否则替换为"小"
result = ['大' if x > 3 else '小' for x in numbers]
print(result)  # ['小', '小', '小', '大', '大', '大']
# 复杂的条件替换
scores = [85, 92, 78, 95, 60]
grades = ['A' if s >= 90 
          else 'B' if s >= 80 
          else 'C' if s >= 70 
          else 'D' 
          for s in scores]
print(grades)  # ['B', 'A', 'C', 'A', 'D']

性能优化技巧

# 1. 避免过多的嵌套,考虑可读性
# 不好的写法
result = [f(x) for x in list1 for y in list2 if condition(x, y) if condition2(x)]
# 好的写法
result = []
for x in list1:
    for y in list2:
        if condition(x, y) and condition2(x):
            result.append(f(x))
# 2. 使用生成器表达式节省内存(大数据集)
# 列表推导式(占用内存)
big_list = [x**2 for x in range(1000000)]
# 生成器表达式(按需生成)
big_generator = (x**2 for x in range(1000000))
# 使用时逐个取值
first_100 = [next(big_generator) for _ in range(100)]

练习题

# 练习1:找出列表中所有偶数的平方
numbers = list(range(1, 11))
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(f"偶数平方: {even_squares}")  # [4, 16, 36, 64, 100]
# 练习2:从字符串列表中提取所有电话号码
data = ['张三: 13800138000', '李四: 你好', '王五: 13912345678']
phones = [item.split(': ')[1] 
          for item in data 
          if item.split(': ')[1].isdigit()]
print(f"电话号码: {phones}")  # ['13800138000', '13912345678']

列表推导式取值的关键点:

  1. 基本语法[表达式 for 变量 in 可迭代对象]
  2. 条件筛选:添加 if 条件
  3. 嵌套处理:使用多个 for 子句
  4. 条件替换:使用三元运算符
  5. 性能考虑:大数据量时考虑生成器

掌握这些技巧,能让你的Python代码更加简洁高效!

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