本文共 1348 字,大约阅读时间需要 4 分钟。
所有代码先加这行解决中文乱码问题
# -*- coding: utf-8 -*-
py2.7: xrange();
py3.x: range();
data = [1,2,3,4,5,6,7,8]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
列表解析更快。大约快两三倍。
from random import randint# 某班有20个人,分数分布在60~100d = {x: randint(60,100) for x in xrange(1,21) }print dprint { k for k in d if k>10}print {v for v in d.values() if v>90}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 randintdata = [randint(-10,10) for _ in xrange(10)]s = set(data) print ssres = {x for x in s if x % 3 == 0}print sres
转载地址:http://oyhwl.baihongyu.com/