在Python中,筛选数组可以通过多种方法实现,以下是几种常见的方法:
1. 使用`filter()`函数:
numbers = [1, 2, 3, 4, 5, 6, 7]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) 输出:[2, 4, 6]
2. 使用布尔索引(适用于NumPy数组):
import numpy as np
a = np.array([1, 2, 3, 4])
condition = a > 2
filtered_array = a[condition]
print(filtered_array) 输出:[3, 4]
3. 使用`numpy.where()`函数:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7])
condition = a > 2
filtered_array = a[np.where(condition)]
print(filtered_array) 输出:[3, 4, 5, 6]
4. 使用列表推导式:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
filtered_matrix = [[row for row in matrix if row > 2] for col in matrix]
print(filtered_matrix) 输出:[, [5, 6], [8, 9]]
5. 使用`numpy.array`和条件表达式:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7])
filtered_array = a[a > 2]
print(filtered_array) 输出:[3, 4, 5, 6]