盒子
盒子

filter

filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

相当于一个过滤函数,根据function的定义筛选出符合function的值,

例如filter(odd, number),的返回值就是number中的所有奇数结果。

可以如下定义,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import random
def filter(bool_func, seq):
filtered_seq = []
for eachitem in seq:
if bool_func(eachitem):
filtered_seq.append(eachitem)
return filtered_seq
def odd(n):
return n % 2
allNums = [i for i in range(100)]
random.shuffle(allNums)
print(filter(odd, allNums))