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

来源:互联网 发布:文章校对软件 编辑:程序博客网 时间:2024/05/15 16:35
##from:liaoxuefeng.com
#mapdef f(x):return x*xfor num in map(f,[1,2,3,4,5]):print(num)#reducefrom functools import reducedef add(x, y):return x + yprint(reduce(add, [1, 3, 5, 7, 9]))#map&redycedef 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 + yfor num in map(char2num,"13594"):print (num)print(reduce(fn,map(char2num,"13594")) )#filterdef 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 ndef _not_divisible(n):    return lambda x: x % n > 0def 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#sortL = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]def by_name(t):return t[0]L2 = sorted(L, key=by_name)print(L2)
#decoratordef log(func):    def wrapper(*args, **kw):        print('call %s():' % func.__name__)        return func(*args, **kw)    return wrapper@logdef data():<span style="white-space:pre"></span>print("2015-7-14")data()#偏函数import functoolsint2=functools.partial(int,base=2)print(int2("110001"))

0 0
原创粉丝点击