您的位置:首页 > 编程语言 > Python开发

Python学习笔记——内置函数

2014-10-11 10:48 525 查看
apply(function,args[,keywords])
The function argument must be a callable object (a user-defined or built-infunction or method, or a class object) and theargs argument must be asequence. Thefunction is called with
args as the argument list; the numberof arguments is the length of the tuple. If the optionalkeywords argument ispresent, it must be a dictionary whose keys are strings. It specifies keywordarguments to be added to the end of the argument
list. Callingapply() isdifferent from
just callingfunction(args), since in that case there isalways exactly one argument. The use ofapply()
is equivalent tofunction(*args,**keywords).

map(function, iterable,...)

Apply function to every item of iterable and return a list of the results.If additionaliterable arguments are passed,
function must take that manyarguments and is applied to the items from all iterables in parallel. If oneiterable is shorter than another it is assumed to be extended withNoneitems. If
function isNone, the identity function is assumed; if thereare multiple arguments,map()
returns a list consisting of tuplescontaining the corresponding items from all iterables (a kind of transposeoperation). Theiterable arguments may be a sequence or any iterable object;the result is always a list.

apply与map的区别,map的参数iterable是依次作为参数,调用function,然后各自的返回值作为一个list,作为map方法的返回值。而apply的args可以是一个list,作为function的参数,一次性的调用function。而apply也不同于function(agrs),apply可以是以字典作为不定参数的版本,相当于function(*args,**keywords)

a = [1,2,3,4,5,6,7,8,9,10]

def calc(*arg):
return 2*arg

def calc2(arg):
return 2*arg

def calc3(arg, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9):
return 2*arg

#map是将参数a这个序列中的每个成员,以此作为参数,调用calc函数,将函数的返回值,依次生成一个list作为map的返回值
#将参数解释为单个数字,返回的也是数字,map的返回值就是一系列数字组成的列表
print map(calc2, a)

#将参数设置为不定参数,输入就解释为元组,calc的返回值就是就是元组,map的返回值就是元组的列表
print map(calc, a)

#apply()是将参数a作为一个整体,调用calc,所以calc必须是10个参数(如calc的版本),或者使用不定参数(参数被解释为元组,如calc3的版本)
print apply(calc, a)

print apply(calc3, a)


执行结果

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)]

(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: