Python高级编程笔记-----map()&reduce()

84 阅读1分钟

map()函数

参数

  1. 函数
  2. Iterable
  • 返回map object

作用效果

将Iterable每一个元素代入函数得出结果,并返回1个map object 函数不一定是自定义函数,也可以是str等函数

# map()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(lambda name: name.capitalize(), L1))
print(L2)

reduce()函数

参数

  1. 函数(必须传两个参)
  2. Iterable
  • 返回正常数据

作用效果

将Iterable每一个元素代入函数并得出结果,并将该结果作为参数与下一个元素一起代入函数直Iterable完毕返回最后值

# reduce()
def prod(L):
    return reduce(lambda x1, x2: x1 * x2, L)
    pass


print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')
# map()&reduce()
exchange = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}


def str2float(num: str) -> float:
    index = num.find('.')
    n = num.replace('.', '')
    return reduce(lambda x1, x2: x1 * 10 + x2, list(map(lambda s: exchange[s], n))) * 0.1 ** index
    pass


print("str2float('123.456') =", str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')

参考文献:廖雪峰的官方网站