
Python中的filter函数
作用
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
此函数接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
语法
filter(function, iterable)
示例
过滤出1~100中平方根是整数的数
import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
newlist = filter(is_sqr, range(1, 101))
print(newlist)
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果