map|reduce|偏函数|装饰器|
#!/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/