lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

    • Python 基础

    • Python 数据库

    • 面向对象

    • Python Web

    • Python 进阶

      • 协程
      • 装饰器
      • decorator
      • filter
      • 列表生成式
      • 进程&线程
      • 生成器
      • 匿名函数
      • map&&reduce
        • map&&reduce
      • venv
  • leetcode

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • python
  • 进阶
2023-07-16
目录

map&&reduce

# map&&reduce

# map

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

## 将 list1 每个元素都做一次平方操作
def f(x):
    return x * x


l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
res = list(map(f, l1))
print(res)
## 将 l1 每个元素转化为字符
res1 = list(map(str, l1))
print(res1)

# 测试

## 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
## 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
def normalize(name):
    res = ''
    for i in range(len(name)):
        if(i==0):
            res += name[i].upper()
        else:
            res += name[i].lower()
    return res

## 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

# reduce

reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是: reduce(f, [x1, x2, x3, x4]) =f(f(f(x1, x2), x3), x4)

  1. 第一个函数需要接收两个参数 进行运算
  2. 第一次会取前两个进行计算,接着这个运算结果会跟第三个元素进行运算,依次类推

# 简单使用

## 使用 reduce 进行累加和
from functools import reduce

l1 = [1, 2, 3, 4, 5]


def add(x, y):
    return x + y


res = reduce(add, l1)
print(res)

# 测试

## Python提供的sum()函数可以接受一个list并求和,
## 请编写一个prod()函数,可以接受一个list并利用reduce()求积:
def prod(L):
    return reduce( lambda x, y: x*y, L)

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')

## 利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
def str2float(s):
    def char2num(c):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[c]

    s1 = s.split('.')
    cal = lambda x, y: x * 10 + y
    ## 整数
    dec = reduce(cal, map(char2num, s1[0]))
    fra = reduce(cal, map(char2num, s1[1])) * pow(10, -1 * len(s1[1]))
    return dec + fra

    
print(str2float('123.456'))
匿名函数
venv

← 匿名函数 venv→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式