复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53""" 模块:python3 filter().py 功能:python3 过滤函数。 参考:https://www.runoob.com/python3/python3-func-filter.html 知识点: 1.filter(function, iterable), Python3 内置函数 filter() 函数用于过滤序列, 过滤掉不符合条件的元素,返回一个迭代器对象, 如果要转换为列表,可以使用 list() 来转换。 function -- 判断函数。 iterable -- 可迭代对象。 可迭代对象的每个元素将作为参数传递给函数进行判断,然后返回 True 或 False, 最后将返回 True 的元素放到新列表中。 返回一个迭代器对象。 """ # 1.过滤出列表中的所有奇数 def is_odd(n): """ 功能:判断 n 是否为 奇数,是,-> True; 否,-> False. :param n: 待判断奇、偶的自然数。 :return: 是奇数-> True;否则-> False. """ return n % 2 == 1 tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # print(tmplist) # <filter object at 0x00000259517C0430> newlist = list(tmplist) print(newlist) # [1, 3, 5, 7, 9] # 2.过滤出1~100中平方根是整数的数 import math def sqrtIsInt(x): """ 功能:判断 x 的平方根是否是整数。 :param x: 待判断的数。 :return: 是 -> True; 否 -> False. """ return math.sqrt(x) % 1 == 0 print("2:") tmplist = filter(sqrtIsInt, range(1, 101)) newlist = list(tmplist) print(newlist) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
最后
以上就是耍酷万宝路最近收集整理的关于python3 filter().py的全部内容,更多相关python3内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复