zoukankan      html  css  js  c++  java
  • Python入门 函数式编程

    高阶函数

    map/reduce

    from functools import reduce
    
    def fn(x, y):
    	return x * 10 + y
    
    def char2num(s):
    	digits = {'0':0, '1':1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}
    	return digits[s]
    
    print(list(map(char2num, "12357")))
    
    print(reduce(fn, map(char2num, "12357")))
    

    编写成一个函数

    from functools import reduce
    
    digits = {'0':0, '1':1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}
    
    def str2int(s):
    	def fn(x,y):
    		return x*10+y
    	def str2num(s):
    		return digits[s]
    	return reduce(fn, map(str2num, s))
    
    print(str2int("987654321"))
    

    lambda表达式改写

    from functools import reduce
    
    digits = {'0':0, '1':1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}
    
    def str2num(s):
    	return digits[s]	
    
    def str2int(s):
    	return reduce(lambda x,y:x*10+y, map(str2num, s))
    
    print(str2int("23718912739"))
    

    filter 过滤

    def odd(n):
    	return n % 2 == 1;
    
    print(list(filter(odd, range(10))))
    

    sorted 排序

    实现降序排列

    def cmp(x):
    	return -x;
    print(sorted(l, key=cmp))
    

    返回函数

    def createCounter():
    	L = [0]
    	def counter():
    		L[0] += 1
    		return L[0]
    	return counter
    
    counterA = createCounter()
    print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
    counterB = createCounter()
    if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
        print('测试通过!')
    else:
        print('测试失败!')
    

    参考文章

    python高阶函数

  • 相关阅读:
    Git教程
    test
    Android中的权限机制
    Android中<uses-library>的理解
    权限机制
    总是听到有人说AndroidX,到底什么是AndroidX?Android和AndroidX的区别
    VMware Tools按钮变灰色,无法安装的解决方法
    VMware Tools (ubuntu系统)安装详细过程与使用
    Android studio常用快捷键
    CVE漏洞分析
  • 原文地址:https://www.cnblogs.com/Draymonder/p/10667468.html
Copyright © 2011-2022 走看看