Filter过滤序列函数 (过滤器)

本人只是初学阶段,在学习过程中的一些笔记。想借此平台也分享给刚刚学习的朋友,如有错的地方欢迎各位大神与高手指点。

例子一:

def f1(x): # 定义判断函数

 if x > 20:

 return True

    else:

 return False

l1 = [1, 2, 3, 40, 23, 19, 99, 61, 14] # 可迭代对象

print(list(filter(f1, l1))) # 输出结果,python3中需要用到list来展示filter的结果


例子二:过滤出1~100中平方根是整数的数

import math

def f1(x):

 return math.sqrt(x) % 1 == 0

s1 = filter(f1, range(1, 101))

print(list(s1))


例子三:过滤出列表中的所有奇数

def f1(x):

 return x % 2 == 1

l1 = range(1, 11)

print(list(filter(f1, l1)))

猜你喜欢

转载自blog.csdn.net/weixin_34273481/article/details/90989139
今日推荐