1. filter(function, sequence) 返回序列,为原序列中能使function返回true的值
>>>a=[1,2,3,4]
>>>filter(lambda x:x%2, a)
[1, 3]
2. map(function, sequence, [sequence...]) 返回序列,为对原序列每个元素分别调用
function获得的值.
可以传入多个序列,但function也要有相应多的参数,如
map(lambda x,y,z:x+y+z,range(1,3),range(3,5),range(5,7))
计算过程为
1+3+5=9
2+4+6=12
返回[9,12]
3. reduce(function,sequence,[init])
返回一个单值为,计算步骤为 :
* 第1个结果=function(sequence[0],sequence[1])
* 第2个结果=function(第1个结果,sequence[2])
* 返回最后一个计算得值
* 如果有init,则先调用function(init,sequence[0])
* sequence只有一个元素时,返回该元素,为空时抛出异常.
如 reduce(lambda x,y:x+y,range(3),99) 的计算为
99+0=99 => 99+1=100 => 100+2=102
>>>a=[1,2,3,4]
>>>filter(lambda x:x%2, a)
[1, 3]
2. map(function, sequence, [sequence...]) 返回序列,为对原序列每个元素分别调用
function获得的值.
可以传入多个序列,但function也要有相应多的参数,如
map(lambda x,y,z:x+y+z,range(1,3),range(3,5),range(5,7))
计算过程为
1+3+5=9
2+4+6=12
返回[9,12]
3. reduce(function,sequence,[init])
返回一个单值为,计算步骤为 :
* 第1个结果=function(sequence[0],sequence[1])
* 第2个结果=function(第1个结果,sequence[2])
* 返回最后一个计算得值
* 如果有init,则先调用function(init,sequence[0])
* sequence只有一个元素时,返回该元素,为空时抛出异常.
如 reduce(lambda x,y:x+y,range(3),99) 的计算为
99+0=99 => 99+1=100 => 100+2=102
返回102
注:实际使用中用内建函数sum来完成这个累加更合适,如这里等价sum(range(3),99)
4. zip用于多个sequence的循环
questions=['name', 'quest', 'favorite color']
answers=['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print 'What is your %s ? It is %s.' % (q,a)
输出:
What is your name ? It is lancelot.
What is your quest ? It is the holy grail.
What is your favorite color ? It is blue.
注:实际使用中用内建函数sum来完成这个累加更合适,如这里等价sum(range(3),99)
4. zip用于多个sequence的循环
questions=['name', 'quest', 'favorite color']
answers=['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print 'What is your %s ? It is %s.' % (q,a)
输出:
What is your name ? It is lancelot.
What is your quest ? It is the holy grail.
What is your favorite color ? It is blue.