Monday, October 17, 2011

[Level 2] map, reduce and filter methods in Python

#!/bin/env python
a = [1,2,3,4,5,6,7,8,9]
b = [1,2,3,4]
c = [5,6,7,8]
 
print filter(lambda x: x>5, a)
print map(lambda x,y: x+y, b, c)
print map(lambda x,y: bool(x) and bool(y), a, b)
print map(lambda x,y: bool(x) or bool(y), b, a)
print reduce(lambda x,y: x+y, a)
$ /tmp/t.py 
[6, 7, 8, 9]
[6, 8, 10, 12]
[True, True, True, True, False, False, False, False, False]
[True, True, True, True, True, True, True, True, True]
45
Wish this helps. regards, Stanley Huang