python学习代码笔记(map,reduce,filter,sort,decorator,functools.partial)

##from:liaoxuefeng.com
#map
def f(x):
	return x*x
for num in map(f,[1,2,3,4,5]):
	print(num)

#reduce
from functools import reduce
def add(x, y):	
	return x + y

print(reduce(add, [1, 3, 5, 7, 9]))

#map&redyce
def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

def fn(x, y):
	return x * 10 + y
for num in map(char2num,"13594"):
	print (num)
print(reduce(fn,map(char2num,"13594")) )


#filter
def not_empty(s):
    return s and s.strip()

for char in list(filter(not_empty, ['A', '', 'B', None, 'C', '  '])):
	print(char)
#######质素
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) # 构造新序列
for n in primes():
    if n < 100:
        print(n)
    else:
        break
#sort
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
	return t[0]
L2 = sorted(L, key=by_name)
print(L2)
#decorator
def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper
@log
def data():
<span style="white-space:pre">	</span>print("2015-7-14")
data()


#偏函数
import functools
int2=functools.partial(int,base=2)
print(int2("110001"))

猜你喜欢

转载自blog.csdn.net/lylhjh/article/details/51938778
今日推荐