|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 zltzlt 于 2020-3-29 12:53 编辑
Python 重构 filter() 函数
要求
1. 完整实现 filter() 的功能
2. 代码中禁止使用 filter() BIF
格式
- def filter(func, iterable):
- # write your code here
复制代码
或
- class filter:
- def __init__(self, func, iterable):
- # your code
- def __iter__(self):
- return self
- def __next__(self):
- # your code
复制代码
例子
- >>> list(filter(None, [True, False, 0, 1, '']))
- [True, 1]
- >>> list(filter(lambda x: x % 2 == 0, range(10)))
- [0, 2, 4, 6, 8]
- >>> for i in filter(lambda x: x != 5, [5, 4, 5, 6, 7, 3, 5]):
- print(i)
-
- 4
- 6
- 7
- 3
复制代码
NOW, IT'S YOUR SHOWTIME !
- def filter(function, iterable,/):
- if function is None:
- for i in iterable:
- if i:
- yield i
-
- else:
- for i in iterable:
- if function(i):
- yield i
复制代码
|
|