前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3_函数式编程

python3_函数式编程

作者头像
yifei_
发布2022-11-14 14:45:32
1750
发布2022-11-14 14:45:32
举报
文章被收录于专栏:yifei的专栏yifei的专栏

map|reduce|偏函数|装饰器|

代码语言:javascript
复制
#!/usr/bin/python3
# -*- coding: utf-8 -*-

print("高阶函数(以函数作为参数)-------------")
def add(x,y,f):
    return f(x)+f(y)

print(add(5,-6,abs))

print("map/reduce-------------")
def normalize(name):
    return name.capitalize()

L1 = ['adam', 'LISA', 'barT']
print(list(map(normalize, L1)))

print("map/reduce-------------")
from functools import reduce
def multi(x,y):
    return x*y

def addone(x):
    return x+1
#map(f,[1,2,3]) 对列表每个成员执行操作f
#reduce(f,[1,2,3]) f(f(1,2),3) 依次计算
print(reduce(multi,map(addone,[1,2,3,1,1,1])))

print("filter-------------")
# filter(f,[1,2,3]) 对列表每一项进行f函数,如果结果为true则保留该值
# list(filter(f,[1,2,3])) 由于filter是惰性求值,需要list才能获得整个列表
def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n
def _not_divisible(n):
    return lambda x: x % n > 0
#埃氏筛法
def primes():
    yield 2
    it = _odd_iter() # 初始序列
    while True:
        n = next(it) # 返回序列的第一个数
        yield n
        it = filter(_not_divisible(n), it) # 构造新序列
# 打印1000以内的素数:
for n in primes():
    if n < 2:
        print(n)
    else:
        break

print("sorted-------------")
#sorted 是python内置排序算法,可以额外接受一个函数
#内部比较两个元素时,按照分别给两个元素执行函数后的结果进行比较
sorted([36, 5, -12, 9, -21], key=abs)

print("闭包-------------")
#要记得_sum()中不应当引用会变化的变量
def sum(a,b):
    x=1
    def _sum():
        return (a+x)*(b+x)
    return _sum
f=sum(1,1)
print(f())

print("lambda-------------")
f=lambda x:x*x
print(f(2))
print(list(map(lambda x:x*x*x,[1,2,3])))

print("装饰器-------------")

def log(func):
    def wrapper(*args,**kw):
        print('call %s' % func.__name__)
        return func(*args,**kw)
    return wrapper

@log
def now():
    print('20191111')

now()

print("偏函数-------------")
print(int('100101001',base=2))
import functools
int2=functools.partial(int,base=2)
print(int2("10001"))
#模块的目录
import sys
print(sys.path)

print("private函数-------------")
def _hello():
    print("hello")
def hello():
    _hello()
hello()

'''
print("pillow库测试-------------")
from PIL import ImageFilter
from PIL import Image

imgF = Image.open("./test.jpg")
outF = imgF.filter(ImageFilter.DETAIL)
conF = imgF.filter(ImageFilter.CONTOUR)
edgeF = imgF.filter(ImageFilter.FIND_EDGES)
imgF.show()
outF.show()
conF.show()
edgeF.show()

参考

欢迎与我分享你的看法。 转载请注明出处:http://taowusheng.cn/

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-11-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档