Python map,reduce,filter,apply

map(functioniterable...)

map()函数接收两个参数,一个是函数,一个是可迭代的对象,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。

基本等价于 [f(x) for x in interable]

>>> map(lambda x:x*2,xrange(4))
[0, 2, 4, 6]
>>> [x*2 for x in xrange(4)]
[0, 2, 4, 6]
>>> l=["far","foo","bar"]
>>> map(lambda x:x.upper(),l)
['FAR', 'FOO', 'BAR']
>>> map(lambda x: "f" in x,l)
[True, True, False]
>>> filter(lambda x:"f" in x,l)
['far', 'foo']
>>> map(lambda x:x.upper(),filter(lambda x:"f" in x,l))
['FAR', 'FOO']
#map 并行

def formular_1(x1,x2,x3):
    return 100*x1+20*x2+x3
    
a=[1,2,3]
b=[-1,-2,-3]
c=[1.0,2.5,3.5]

map(formular_1,a,b,c)

[81.0, 162.5, 243.5]
#当fun为None,就类似zip
map(None,a,b,c)
[(1, -1, 1.0), (2, -2, 2.5), (3, -3, 3.5)]

reduce( func, seq[, init] )

reduce函数即为化简,它是这样一个过程:每次迭代,将上一次的迭代结果(第一次时为init的元素,如没有init则为seq的第一个元素)与下一个元素一同执行一个二元的func函数。在reduce函数中,init是可选的,如果使用,则作为第一次迭代的第一个元素使用。

这里面函数必须有俩个参数。

reduce(lambda x,y :x*y,xrange(1,10))
362880
reduce(lambda x,y :x*y,xrange(1,10),0.5)
181440.0

filter( func, seq )

该内建函数的作用相当于一个筛子。func函数是一个布尔函数,filter()调用这个布尔函数,将每个seq中的元素依次过一遍筛子,选出使func返回值是Ture的元素的序列。

scores=[49,59,50,66,89,100]
def score_filter(score):
    return score>=80
#1
result=[]
for score in scores:
    if score_filter(score):
        result.append(score)

[89, 100]

#2 

filter(score_filter,scores)

[89, 100]

#3  list comprehension 列表表达式

[score for score in scores if score>=80]

[89, 100]
filter(lambda s:s and s.strip(),["A","",None,"C"])

['A', 'C']

apply(func [, args [, kwargs ]])

函数用于当函数参数已经存在于一个元组或字典中时,间接地调用函数。args是一个包含将要提供给函数的按位置传递的参数的元组。如果省略了args,任 何参数都不会被传递,kwargs是一个包含关键字参数的字典。apply()的返回值就是func()的返回值,apply()的元素参数是有序的,元素的顺序必须和func()形式参数的顺序一致

然而,由于目前的Python中,已经可以在函数调用中使用非关键字参数和关键字参数作为可变长参数调用,apply()已经被从Python1.6开始被摒弃淘汰。因此,此处仅对该函数进行一个大致的介绍,而不具体深入,也不应在编程中再使用该函数

def say():
  print 'say in'

apply(say)

say in


def fun_add(x):
    print str(x)
    
apply(fun_add,("1"))

1


def say(a, b):
  print a, b
 
apply(say,("hello", "python"))

hello python
原文地址:https://www.cnblogs.com/dadadechengzi/p/6268495.html