上帝大脸 发表于 2017-5-6 09:55:21

python的几个内建函数:apply(),filter(),map(),reduce()

  apply()函数:apply(func[,nkw][,kw]) 它的返回值就是func函数的返回值
  
filter()函数:filter(func,seq)调用bool函数func,遍历处理序列中seq的每个元素。它的返回值是一个序列,其元素都是让func函数返回true值的原seq序列中的元素
  map()函数:
  def map(func,seq):
mapped_seq = []
for eachItem in seq:
mapped_seq.append(apply(func,eachItem))
return mapped_seq
  
reduce()函数:reduce(func,seq[,init]),用二元函数func对序列seq中的元素进行处理,每次处理两个数据项(一个是前次处理的结果,一个是序列中的下一个元素),如此反复的递归处理,最后对整个序列求出一个单一的返回值。
  1.apply()函数
  1.1 apply()函数对于调用那些参数是动态生成的函数是非常方便的,一般牵扯到拼凑一个参数清单这种问题
  matheasy.py
  #!/usr/bin/env/ python
from string import lower
from operator import add,sub,mul
from random import randint,choice
  ops = {'+':add,'-':sub,'*':mul}
MAXTRIES = 2
  def doprob():
op = choice('+-*')
nums =
nums.sort();nums.reverse()
ans = apply(ops,nums)
pr = '%d %s %d = ' %( nums,op,nums)
oops = 0
while 1:
try:
if int(raw_input(pr)) == ans:
print "correct"
break
if oops == MAXTRIES:
print 'answer\n%s%d' %(pr,ans)
break
else:
print 'incorrect ... try again'
oops = oops + 1
except(KeyboardInterrupt,EOFError,ValueError):
print 'invalid input data ... try again'

def main():
print 'welcome to play this game:'
while 1:
doprob()
try:
opt = lower(raw_input('Try again? (/n)'))
except(KeyboardInterrupt,EOFError):
print ;break
if opt and opt =='n':
print 'quit the game,byebye'
break
  if __name__ == '__main__':
main()






1.2 apply()函数对于应用程序的调试纠错和性能测试方面也是很有用的。一般是编写一个诊断性函数来建立测试环境,然后调用准备对它进行测试的函数,考虑到系统的灵活性和适应性,被测试函数作为一个参数传递进去
  testit.py
  #!/usr/bin/env/ python
def testit(funcname,*nkwargs,**kwargs):
try:
retval = apply(funcname,nkwargs,kwargs)
result = (1,retval)
except Exception,diag:
result = (0,str(diag))
return result
  def test():
funcs = (int,long,float)
vals = (1234,12.34,'1234','12.34')

for eachFunc in funcs:
print '-'*40
for eachVal in vals:
retval = testit(eachFunc,eachVal)

if retval:
print '%s(%s) = ' %(eachFunc.__name__,eachVal),retval
else:
print '%s(%s) = FAILED ' %(eachFunc.__name__,eachVal),retval

if __name__ == '__main__':
test()

  2.filter()函数
  oddnumgen.py
  from random import randint
def odd():
allNums = []
for eachNum in range(100):
allNums.append(randint(1,1000))
oddNums = filter(lambda n:n%2,allNums)
print "length of sequence = %d\n" %(len(oddNums)),oddNums
  3.map()函数
  >>>map(lambda x,y:(x+y,x-y),,)
>>> [(3, -1), (7, -1), (11, -1)]
  from string import strip,upper
def strupper():
f = open('map.txt')
lines = f.readlines()
f.close()
print ' ... BEFORE processing ...'
for eachLine in lines:
print '<%s>' %eachLine[:-1]#去掉换行符
print "\n"
print ' ... AFTER processing ...'
for eachLine in map(upper,map(strip,lines)):#strip不清理字符串之间的空格
print '<%s>' %eachLine
  def rounder():
f = open('round.txt')
values = map(float,f.readlines())
f.close()

print 'original\trounded'
for eachVal in map(None,values,map(round,values)):#函数为None,那么参数列表中的n个序列(此时为values和map(round,values) )组成了返回值的列表
print '%6.02f\t\t%6.02f' %eachVal
  4.reduce()函数
  >>> print 'the total is:',total = reduce((lambda x,y:x+y),range(1000))
页: [1]
查看完整版本: python的几个内建函数:apply(),filter(),map(),reduce()