【常用总结】用Python对数据结构进行个性化过滤操作

法1:列表推导式

法2:高阶函数

法3:循环遍历

# 法1:推导式 —— (过滤列表) 
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)  # 输出 [2, 4, 6, 8, 10]

# 法1:推导式 —— 过滤NumPy数组
import numpy as np

numbers = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
even_numbers = numbers[numbers % 2 == 0]
print(even_numbers)  # 输出 [2 4 6 8 10]

# 法1:推导式 —— 过滤元组
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
even_numbers = tuple(x for x in numbers if x % 2 == 0)
print(even_numbers)  # 输出 (2, 4, 6, 8, 10)

# 法1:字典推导式
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 95}
passed_students = { name: score for name, score in scores.items() if score >= 80}
print(passed_students)  # 输出 {'Alice': 85, 'Bob': 92, 'David': 95}

# 法2:高阶函数 —— (过滤列表)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 输出 [2, 4, 6, 8, 10]


# 法2:高阶函数 —— (过滤字典)
students = [
    {'name': 'Alice', 'age': 20, 'grade': 'A'},
    {'name': 'Bob', 'age': 19, 'grade': 'B'},
    {'name': 'Charlie', 'age': 21, 'grade': 'A'},
    {'name': 'David', 'age': 18, 'grade': 'C'}
]

# 过滤出年龄大于等于20岁的学生
filtered_students = list( filter(lambda student: student['age'] >= 19, students))
print(filtered_students)
# 输出: [{'name': 'Alice', 'age': 20, 'grade': 'A'}, {'name': 'Charlie', 'age': 21, 'grade': 'A'}]

# 过滤出成绩为'A'的学生
filtered_students = list(filter(lambda student: student['grade'] == 'A', students))
print(filtered_students)
# 输出: [{'name': 'Alice', 'age': 20, 'grade': 'A'}, {'name': 'Charlie', 'age': 21, 'grade': 'A'}]


# 法3:循环遍历 —— (过滤列表)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)
print(even_numbers)  # 输出 [2, 4, 6, 8, 10]


# 法3:循环遍历 —— (过滤字典)

scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 95}
passed_students = {}
for name, score in scores.items():
    if score >= 80:
        passed_students[name] = score
print(passed_students)  # 输出 {'Alice': 85, 'Bob': 92, 'David': 95}



你可能感兴趣的:(python,数据结构,开发语言)