1.列表
[x for x in data if x >= 0] #列表解析
filter(lambda x: x >= 0, data) #filter解析
2.字典
{k: v for k, v in d.items() if v > 90}
3.集合
{x for x in s if x % 3 == 0}
举例1
from random import randint
randint?
randint? :打印函数信息
l = [randint(-10, 10) for _ in range(10)]
[x for x in l if x >= 0] #筛选数据
执行结果:[5, 9, 10]
g = filter(lambda x: x >= 0, l)
next(g)
执行结果:5
python2.7:filter直接返回列表;python3:返回生成器对象,生成器对象是一次性的
g = filter(lambda x: x >= 0, l) #筛选数据
list(g)
执行结果:[5, 9, 10]
一般使用列表解析,filter相对慢
举例2
d = {'student%d' % i: randint(50, 100) for i in range(1, 21)}
{k : v for k, v in d.items() if v >= 90} #筛选数据
执行结果:{'student2': 94,
'student9': 99,
'student15': 95,
'student16': 92,
'student18': 97,
'student20': 96}
#使用filter
g = filter(lambda item: item[1] >= 90, d.items()) #筛选数据
list(g)
执行结果:[('student2', 94),
('student9', 99),
('student15', 95),
('student16', 92),
('student18', 97),
('student20', 96)]
g = filter(lambda item: item[1] >= 90, d.items()) #筛选数据
dict(g)
执行结果:{'student2': 94,
'student9': 99,
'student15': 95,
'student16': 92,
'student18': 97,
'student20': 96}
举例3
s = {randint(0, 20) for _ in range(20)}
s
执行结果:{0, 1, 2, 3, 4, 9, 10, 12, 13, 18, 19}
{x for x in s if x % 3 == 0} #筛选数据
执行结果:{0, 3, 9, 12, 18}