法1:列表推导式
法2:高阶函数
法3:循环遍历
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)
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)
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)
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)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
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'}
]
filtered_students = list( filter(lambda student: student['age'] >= 19, students))
print(filtered_students)
filtered_students = list(filter(lambda student: student['grade'] == 'A', students))
print(filtered_students)
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)
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)