以下是一个使用按键值过滤数组的示例代码解决方法:
def filter_array(arr, key):
filtered_array = []
for item in arr:
if item == key:
filtered_array.append(item)
return filtered_array
# 示例用法
arr = [1, 2, 3, 4, 5, 2, 2]
key = 2
filtered = filter_array(arr, key)
print(filtered) # 输出:[2, 2, 2]
在这个示例中,filter_array
函数接受一个数组和一个键作为输入,并返回一个新的过滤后的数组。函数遍历输入的数组,将与键相等的元素添加到新的数组中,并返回它。在示例用法中,我们使用示例数组arr
和键key=2
来过滤数组,并打印结果。
上一篇:按键值过滤对象数组为数组