# Python学习笔记（5）：lambda,filter,map,reduce,zip用法整理

## lambda用法例子：

1. >>> g = lambda x, y, z : (x + y) ** z
2. >>> print g(1,2,2)
3. 9


1. >>> list_a = [lambda a: a**3, lambda b: b**3]
2. >>> g = list_a[0]
3. >>> g(2)
4. 8


## map用法例子：

1. >>> print map(lambda x , y : x ** y, [2,4,6],[3,2,1])
2. [8, 16, 6]


1. >>> print map(None, [2,4,6],[3,2,1])
2. [(2, 3), (4, 2), (6, 1)]


1. >>> map(int, (1,2,3))
2. [1, 2, 3]


1. >>> map(int, '1234')
2. [1, 2, 3, 4]


1. >>> map(int, {1:2,2:3,3:4})
2. [1, 2, 3]


1. >>> map(tuple, 'agdf')
2. [('a',), ('g',), ('d',), ('f',)]


1. >>>def square(x) : # 计算平方数
2. ... return x ** 2 ...
3. >>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
4. [1, 4, 9, 16, 25]


1. >>> listx = [1,2,3,4,5,6,7] # 7 个元素
2. >>> listy = [2,3,4,5,6,7] # 6 个元素
3. >>> listz = [100,100,100,100] # 4 个元素
4. >>> list_result = map(lambda x,y,z : x**2 + y + z,listx, listy, listz)
5. >>> print(list(list_result))
6. [103, 107, 113, 121]


## reduce用法例子：

1. >>> print reduce(lambda x, y: x * y, range(1, 6))
2. 120


1. >>> print (reduce(lambda x, y: x * y, range(1, 6),3))
2. 360


1. >>> from functools import reduce
2. >>> def fn(x, y):
3.           ... return x * 10 + y
4. >>> def char2num(s):
5.          ... digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
6.          ... return digits[s]
7. >>> reduce(fn, map(char2num, '13579'))
8. 13579


## filter用法例子：

1. >>> def f(x):
2.         ...return x % 2 != 0 and x % 3 != 0
3. >>> filter(f, range(2, 25))
4. [5, 7, 11, 13, 17, 19, 23]


1. >>>l =[1,2,3,4]
2. >>>filter(lambda x: x>2, l)
3. [3, 4]


## zip 用法例子：

1. >>> a = [1,2,3]
2. >>> b = [4,5,6]
3. >>> zipped = zip(a,b)
4. [(1, 4), (2, 5), (3, 6)]


1. >>> x = [1,2,3]
2. >>> y = ['a','b','c']
3. >>> z = [4,5,6]
4. >>> zip_xyz = zip(x, y, z)
5. >>> print zip_xyz
6. [(1, 'a', 4), (2, 'b', 5), (3, 'c', 6)]


1. >>> a = [1,2,3]
2. >>> b = [4,5,6,7]
3. >>> zip_ab = zip(a, b)
4. >>> print zip_ab
5. [(1, 4), (2, 5), (3, 6)]


1. >>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2. >>> zip(*a)[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
3. >>> map(list,zip(*a))
4. [[1, 4, 7], [2, 5, 8], [3, 6, 9]]


1. >>>l1 = [1, 2, 3, 4]
2. >>>l2 = ['a', 'b', 'c', 'd']
3. >>>zip_l1_l2 = zip(l1,l2)
4. >>>zip(*zip_l1_l2)
5. [(1, 2, 3, 4), ('a', 'b', 'c', 'd')]


1. >>>l1 = [1, 2, 3, 4]
2. >>>l2 = ['a', 'b', 'c', 'd']
3. >>>zip_l1_l2 = zip(l1,l2)
4. >>>dict(zip_l1_l2)
5. {1: 'a', 2: 'b', 3: 'c', 4: 'd'}