def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("-----filter -> 外置函数过滤-----")
even_numbers = list(filter(is_even, numbers))
print(even_numbers)
输出:
[2, 4, 6, 8, 10]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("-----filter过滤 -> lambda过滤-----")
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
输出:
[2, 4, 6, 8, 10]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("-----列式推导过滤-----")
even_numbers = [x for x in numbers if (x % 2 == 0)]
print(even_numbers)
输出:
[2, 4, 6, 8, 10]