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"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值