Python列表筛选案例如何过滤数据

wen python案例 32

本文目录导读:

Python列表筛选案例如何过滤数据

  1. 使用列表推导式(最常用)
  2. 使用 filter() 函数
  3. 筛选字典列表
  4. 多条件筛选
  5. 实际应用案例
  6. 性能对比与推荐
  7. 总结建议

我来介绍几种Python列表筛选数据的常用方法。

使用列表推导式(最常用)

# 筛选偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)  # [2, 4, 6, 8, 10]
# 筛选包含特定字符的字符串
words = ['python', 'java', 'javascript', 'php', 'ruby']
py_words = [w for w in words if 'py' in w.lower()]
print(py_words)  # ['python']

使用 filter() 函数

# 筛选大于5的数
numbers = [1, 3, 5, 7, 9, 11]
def is_greater_than_5(x):
    return x > 5
result = list(filter(is_greater_than_5, numbers))
print(result)  # [7, 9, 11]
# 使用lambda表达式
result = list(filter(lambda x: x > 5, numbers))
print(result)  # [7, 9, 11]

筛选字典列表

# 筛选学生成绩
students = [
    {'name': '张三', 'score': 85, 'age': 20},
    {'name': '李四', 'score': 92, 'age': 22},
    {'name': '王五', 'score': 78, 'age': 19},
    {'name': '赵六', 'score': 95, 'age': 21}
]
# 筛选成绩大于80的学生
high_scores = [s for s in students if s['score'] > 80]
print("高分学生:", high_scores)
# 筛选年龄大于20且成绩大于90的学生
filtered = [s for s in students if s['age'] > 20 and s['score'] > 90]
print("符合条件的学生:", filtered)

多条件筛选

# 多条件组合筛选
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# 筛选能被2或3整除的数
result1 = [n for n in numbers if n % 2 == 0 or n % 3 == 0]
print("能被2或3整除:", result1)
# 筛选能被2和3整除的数(即能被6整除)
result2 = [n for n in numbers if n % 2 == 0 and n % 3 == 0]
print("能被2和3整除:", result2)
# 复杂条件
result3 = [n for n in numbers if 3 < n < 10 and n != 5]
print("3到10之间且不等于5:", result3)

实际应用案例

# 案例1:筛选有效邮箱
emails = [
    'user@example.com',
    'invalid-email',
    'admin@test.com',
    'user@',
    '@domain.com'
]
def is_valid_email(email):
    return '@' in email and '.' in email.split('@')[-1]
valid_emails = [e for e in emails if is_valid_email(e)]
print("有效邮箱:", valid_emails)
# 案例2:筛选价格区间内的商品
products = [
    {'name': '手机', 'price': 3999},
    {'name': '电脑', 'price': 6999},
    {'name': '平板', 'price': 2999},
    {'name': '耳机', 'price': 199}
]
# 筛选价格在1000-4000之间的商品
affordable = [p for p in products if 1000 <= p['price'] <= 4000]
print("价格适中的商品:", affordable)
# 案例3:文本数据筛选
sentences = [
    "Python是一门优秀的编程语言",
    "今天天气真好",
    "学习Python让生活更美好",
    "这是最后一条"
]
# 筛选包含"Python"的句子
python_sentences = [s for s in sentences if 'Python' in s]
print("包含Python的句子:", python_sentences)

性能对比与推荐

import time
# 大数据量测试
data = list(range(1000000))
# 列表推导式(推荐)
start = time.time()
result1 = [x for x in data if x > 500000]
print("列表推导式:", time.time() - start)
# filter函数
start = time.time()
result2 = list(filter(lambda x: x > 500000, data))
print("filter:", time.time() - start)
# 手动循环(最慢)
start = time.time()
result3 = []
for x in data:
    if x > 500000:
        result3.append(x)
print("手动循环:", time.time() - start)

总结建议

  1. 简单条件筛选:使用列表推导式,代码简洁高效
  2. 复杂逻辑筛选:使用 filter() + 自定义函数,可读性更好
  3. 字典列表筛选:列表推导式配合条件判断很实用
  4. 大数据量处理:考虑使用 numpy 或 pandas 等库

选择哪种方法主要取决于:

  • 代码可读性
  • 数据规模
  • 筛选条件的复杂度

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