map函数是用于函数式编程的Python内置函数中最简单的一个。map()将指定的函数应用于迭代中的每个元素 ,下面的代码计算list中每个单词的长度
names = ['Fred', 'Wilma', 'Barney']
c=list(map(len, names))
print(c)
#输出:
[4, 5, 6]
与匿名函数:
names = ['Fred', 'Wilma', 'Barney']
c=list(map(lambda x:x*2, [1, 2, 3, 4, 5]))
print(c)
#输出:
[2, 4, 6, 8, 10]
自定义函数:
def to_percent(num):
return num * 100
print(list(map(to_percent, [0.95, 0.75, 1.01, 0.1])))
#输出:
[95.0, 75.0, 101.0, 10.0]
例如计算多个迭代的第i个元素的平均值 :
return float(sum(args)) / len(args)
如果列表的个数不一致,会计算已有的:
import operator
measurement1 = [100, 111, 99, 97]
measurement2 = [102, 117]
# 元素间差值计算
print(list(map(operator.sub, measurement1, measurement2)))
# 输出: [-2, -6]
print(list(map(operator.sub, measurement2, measurement1)))
# 输出: [2, 6]