目的

掌握map, reduce的应用

实现

一些代码训练

代码

  from functools import reduce
  
  # map
  l = map(str, [1, 2, 3, 4, 6])
  print(list(l))
  
  
  # reduce() r的值等于1*2*3.....*100
  def sumNum(x, y):
      return x * y
  
  
  list1 = (range(1, 101))
  r = reduce(sumNum, list1)
  print(r)
  
  
  # map reduce联合用法
  def str2Int(str):
      def fc(x, y):
          return x * 10 + y
  
      def fs(chr):
          return {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}[chr]
  
      return reduce(fc, map(fs, list(str)))
  
  
  a = str2Int("1234678")
  print(a)