python map和reduce的用法
发布网友
发布时间:2022-04-23 02:27
我来回答
共2个回答
懂视网
时间:2022-05-10 11:51
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']。
1 def cg(name):2 return name[0].upper()+name[1:].lower()3 L = ['adam', 'LISA', 'barT']4 print map(cg,L1)
View Code
编写一个prod()
函数,可以接受一个list并利用reduce()
求积。
1 def prod(num1,num2):2 return num1*num23 L = [3,7,5,9]4 print reduce(prod,L)
View Code
热心网友
时间:2022-05-10 08:59
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).
rece(...)
rece(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to rece the sequence to a single value.
For example, rece(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.