- 通用做法 ----利用循环遍历判断
data = [1,3,5,7,9,11]
res = []
for x in data:
if x >= 2:
res.append(x)
print res
- 函数式编程/列表解析/字典解析/集合解析
#函数式编程
res = filter(lambda x:x>=2,data)
print res
#列表解析
res = [x for x in data if x>=2]
print res
#字典解析
dic = {'a':23,'b':98,'c':0}
res = {k:v for k,v in dic.iteritems() if v>90}
print res
#集合解析
s = (1,2,3,4,5,6,7,8)
res = {x for x in data if x>=2}
print res
- 三个实例
- 列表解析
from random import randint
#使用列表生成式生成10个元素
data = [randint(-10,10) for _ in xrange(10)]
print data
#filter(func,sequence)
res = filter(lambda x:x>=0,data)
print res
# 列表解析
res = [x for x in data if x>=0]
print res
#Time: filter&列表解析
#>>>代表在ipython下
#>>> timeit filter(lambda x:x>=0,data)
#>>> timeit [x for x in data if x>=0]
# 结果:列表解析:432ns(纳秒)
# filter :1.4us(微秒)=1400ns
# 1微秒等于1000纳秒
res = [x for x in data if x>=0]
print res
列表解析更快,用timeit测试
- 字典解析
from random import randint
# 某班有20个人,分数分布在60~100
d = {x: randint(60,100) for x in xrange(1,21) }
print d
print { k for k in d if k>15}
#循环值
print {v for v in d.values() if v>80}
#循环键
print {k for k in d.keys() if k>10}
#循环键和值
res = {k:v for k,v in d.iteritems() if v>90}
print res
- 集合解析
from random import randint
data = [randint(-10,10) for _ in xrange(10)]
s = set(data)
print s
sres = {x for x in s if x % 3 == 0}
print sres
网友评论