Python函数编程语言特性

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  functional.py
#  
def foo(x,y,* args):
	sum = x + y
	for n in args:
		sum += n
	return sum

#apply, filter, map, reduce
def main():
	print foo(1,2,3,4)
	print apply(foo,[1,2,3,4,5])	#apply是用于调用一个函数,函数本身也作为参数
	
	#filter(func,seq),用函数判断序列中的元素是否合条件,为True,则选中,返回符合条件的list
	print filter(lambda x : x % 2, [x for x in range(10)]) 		
	
	#map(func,seq),用函数应用到序列的每个元素中,并将所有结果组合成list返回
	print map(lambda x : x * 2, [x for x in range(10)]) 		
	
	print map(lambda x, y: x + y, [1,3,5], [2,4,6])

	print map(lambda x, y: (x+y, x-y), [1,3,5], [2,4,6])

	print map(None, [1,3,5], [2,4,6])
	
	#reduce 可以视为 reduce(func,x,y,z...) <=> func(func(x,y),z)...
	print reduce(lambda x,y:x+y, [x for x in range(10)])
	
	
	print  [x for x in range(10)]
	return 0

if __name__ == '__main__':
	main()

 

posted @ 2013-04-25 02:23  庚武  Views(245)  Comments(0Edit  收藏  举报