python中的filter()函数的用法

filter函数是一个python的内置函数,用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象

filter(function, iterable)

  • function -- 判断函数。
  • iterable -- 可迭代对象。

如果function 返回True 则将当前值加入新的可迭代对象中

举例:一个列表[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],我们想获取列表内的所有奇数元素

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def is_odd(n):
    if n % 2 != 0:
        return True
    return False

new_list = filter(is_odd, a) 

# new_list是一个可以迭代的对象
for i in new_list:
    print(i)

结果如下:

猜你喜欢

转载自blog.csdn.net/qq_39197555/article/details/112203962