首页 > 代码库 > python 笔记
python 笔记
# coding=utf-8
import math
# 把函数作为参数
def add(x, y, f):
return f(x) + f(y)
# list 遍历执行函数
def format_name(s):
return s[0].upper() + s[1:].lower()
# list求积
def prod(x, y):
return x * y
# 过滤函数
def is_sqr(x):
r = int(math.sqrt(x))
return r*r == x
# 自定义排序
def cmp_ignore_case(s1, s2):
u1 = s1.upper()
u2 = s2.upper()
if u1 < u2:
return -1
elif u1 > u2:
return 1
else:
return 0
# 返回函数
def calc_prod(lst):
def lazy_prod():
def f(x, y):
return x * y
return reduce(f, lst, 1)
return lazy_prod
# 闭包
def count():
fs = []
for i in range(1, 4):
def f(j):
def g():
return j*j
return g
r = f(i)
fs.append(r)
return fs
# 匿名函数
# b = lambda x: x * x
def fff(x):
return x * x
# 装饰器
import time
def performance(f):
def fn(*args, **kw):
t1 = time.time()
r = f(*args, **kw)
t2 = time.time()
print ‘call %s() in %fs‘ % (f.__name__, (t2 - t1))
return r
return fn
@performance
def factorial(n):
return reduce(lambda x, y: x*y, range(1, n+1))
if __name__ == "__main__":
a = add(25, 9, math.sqrt)
m = map(format_name, [‘adam‘, ‘LISA‘, ‘barT‘])
r = reduce(prod, [2, 4, 5, 7, 12])
f = filter(is_sqr, range(1, 101))
s = sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], cmp_ignore_case)
c = calc_prod([1, 2, 3, 4])
f1, f2, f3 = count()
fa = factorial(10)
print fa
python 笔记