Python学习备忘3

来源:互联网 发布:js urldecode解码 编辑:程序博客网 时间:2024/06/15 01:04

    • mapreduce
    • filter
    • sorted

map/reduce

  • map函数
>>> def f(x):    return x*x>>> r = map(f,[1,2,3,4,5,6,7,8,9])>>> list(r) #r是一个Iterator因此通过list()函数让它把整个序列都计算出来并返回一个list[1, 4, 9, 16, 25, 36, 49, 64, 81]
  • reduce函数
    reduce把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
  • str2int函数
from functools import reducedef str2int(s):    def fn(x, y):        return x * 10 + y    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] #等同于t =  {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} #return t[s]    return reduce(fn, map(char2num, s))

或者进一步简化为

from functools import reducedef 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 str2int(s):    return reduce(lambda x, y: x * 10 + y, map(char2num, s)) #lambda为匿名函数,lambda语句中,冒号前是参数,可以有多个,用逗号隔开,冒号右边的返回值。lambda语句构建的其实是一个函数对象
  • 首字母大写函数
def normalize(name):    return name.capitalize()# 测试:L1 = ['adam', 'LISA', 'barT']L2 = list(map(normalize, L1))print(L2)
  • 求list的积
from functools import reducedef prod(L):    return reduce(lambda x,y: x*y ,L)print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
  • str2float
from functools import reducedef str2float(s):    sn = s.split('.')[0]+s.split('.')[-1]    #sn = '123456'    def char2num(sn):        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[sn]    def str2int(sn):        return reduce(lambda x, y: x * 10 + y, map(char2num, sn))     # sn = 123456    return str2int(sn)/pow(10,len(s)-s.index('.')-1)    # pow(10,len(s)-s.index('.')-1的结果是pow(10,3)=1000,123456/1000=123.456 index是求小数点的位置为3print('str2float(\'123.456\') =', str2float('123.456'))

filter

过滤元素,与map类似,输入一个函数和一个List

  • 过滤字符串中的空格
def not_empty(s):    return s and s.strip()#strip是去除字符串的空格,return语句中的and 相当于 if s then s.strip()list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))# 结果: ['A', 'B', 'C']
  • 求素数
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)#返回初始序列3开始的奇数序列        yield n        it = filter(_not_divisible(n),it) # 构造新序列for n in primes():    if n < 1000:        print(n)    else:        break
  • 回数 类似12321
def is_palindrome(n):    n=str(n)    return n[:] ==n[::-1]output = filter(is_palindrome, range(1, 1000))print(list(output))

sorted

key函数,反向排序

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)['Zoo', 'Credit', 'bob', 'about']

tuple按照名字和成绩排序

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]def by_name(t):    return t[0]L2 = sorted(L, key=by_name)print(L2)def by_score(t):    return -t[1]L3 =sorted(L,key=by_score)print(L3)
0 0