快速建立匿名单行最小函数,对数据进行简单处理, 经常与 map(), reduce(), filter() 联合使用。ide
>>> def f (x): return x**2 ... >>> print f(8) 64 >>> >>> g = lambda x: x**2 # 匿名函数默认冒号前面为参数(多个参数用逗号分开), return 冒号后面的表达式 >>> >>> print g(8) 64
与通常函数嵌套,能够产生多个功能相似的的函数。函数
>>> def make_incrementor (n): return lambda x: x + n >>> >>> f = make_incrementor(2) >>> g = make_incrementor(6) >>> >>> print f(42), g(42) 44 48 >>> >>> print make_incrementor(22)(33) 55
filter(function or None, sequence) -> list, tuple, or stringspa
map(function, sequence[, sequence, ...]) -> listcode
reduce(function, sequence[, initial]) -> valueblog
>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] >>> >>> print filter(lambda x: x % 3 == 0, foo) [18, 9, 24, 12, 27] >>> >>> print map(lambda x: x * 2 + 10, foo) [14, 46, 28, 54, 44, 58, 26, 34, 64] >>> >>> print reduce(lambda x, y: x + y, foo) # return (((((a+b)+c)+d)+e)+f) equal to sum() 139
a) 求素数element
>>> nums = range(2, 50) >>> for i in range(2, 8): ... nums = filter(lambda x: x == i or x % i, nums) ... >>> print nums [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
注释: "Leave the element in the list if it is equal to i, or if it leaves a non-zero remainder when divided by i. Otherwise remove it from the list." 从 2 到 7 循环,每次把倍数移除。rem
b) 求单词长度get
>>> sentence = 'It is raining cats and dogs' >>> words = sentence.split() >>> print words ['It', 'is', 'raining', 'cats', 'and', 'dogs'] >>> >>> lengths = map(lambda word: len(word), words) >>> print lengths [2, 2, 7, 4, 3, 4]
参考资料:string