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高阶函数

  • 相关阅读:
    hadoop作业
    爬虫综合大作业
    爬取全部校园新闻
    理解爬虫原理
    中文词频统计与词云生成
    复合数据类型,英文词频统计
    字符串操作、文件操作,英文词频统计预处理
    了解大数据的特点、来源与数据呈现方式
    Hadoop综合大作业
    分布式文件系统HDFS
  • 原文地址:https://www.cnblogs.com/Draymonder/p/10667468.html
Copyright © 2011-2022 走看看