python filter()函数

描述:

  • filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表
  • 接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,返回True或False,将返回True的元素放到新列表中。

语法:

filter(function, iterable)

参数:

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

返回值:

  • 列表

实例:

# 过滤列表中所有奇数

def is_odd(n):
    return n % 2 == 1

newlist = list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(newlist)

 输出结果:

[1, 3, 5, 7, 9]

# 过滤出1~100中平方根是整数的数:

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0

newlist = list(filter(is_sqrt, range(1, 101)))
print(newlist) 

 输出结果:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

当出现这种错误时,是因为没将filter函数转换成list。

原文地址:https://www.cnblogs.com/keye/p/7777018.html