map()
函数接收两个参数,一个是函数,一个是序列,map
将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。def num(x):
return x*xprint map(num,[1,2,3,4,5,6,7,8,9])
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce()
把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:def add(x,y):
return x+yprint reduce(add,[1,3,5,7,9])
#25
def list2num(x,y):
return x*10+yprint reduce(list2num,[1,3,5,7,9])
#13579
sorted()
函数就可以对list进行排序:print sorted([3,6,8,9,4,1,2])
#[1, 2, 3, 4, 6, 8, 9]def reversed_cmp(x,y):
if x>y:
return -1
else:
return 1
return 0print sorted([3,6,8,9,4,1,2],reversed_cmp)
# [9, 8, 6, 4, 3, 2, 1]
python中得闭包,和javascript中很类似:
def lazy_sum(*args):
def s():
return sum([x for x in args])
return sf = lazy_sum(1,2,3,4,5)
print f()
# 15
f2 = lazy_sum()print f2()
# 0
通过lambda实现匿名函数:
f = lambda x: x*x
print f(5)
# 25