美文网首页ITS·黑客
【python】高阶函数:map/reduce/filter/s

【python】高阶函数:map/reduce/filter/s

作者: 某米狼 | 来源:发表于2017-04-12 10:51 被阅读151次

函数式编程咯的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数!

  • 变量可以指向函数,可通过该变量来调用这个函数。f = abs f(-10) #10
  • 函数名就是指向函数的变量,把函数名指向别的内容,就不能再正确使用这个函数了abs = 10 abs(-10) #报错
  • 高阶函数,就是让函数的参数能够接收别的函数。
def add(x, y, f):
    return f(x) + f(y)
>>> add(-5, 6, abs)
11

注:要恢复函数名请重启环境
注:由于abs函数实际上是定义在import builtins模块中的,所以要让修改abs变量的指向在其它模块也生效,要用import builtins; builtins.abs = 10

map

map(func, *iterables) -> object
map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']

reduce

reduce(function, sequence[, initial]) -> value 返回的是值
reduce把一个函数作用在一个序列上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).

>>> from functools import reduce
>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25

练习题

利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:

# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
    s=s.split('.') 
    def char2num(c):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[c]
    return reduce(lambda x,y:x*10+y,map(char2num,s[0]))+reduce(lambda x,y:x*0.1+y,map(char2num,s[1][::-1]))/10
print('str2float(\'123.456\') =', str2float('123.456'))

思路是:把s变成整数部分和小数部分字符串,分别把两个字符串变成数字再相加。
reduce(lambda x,y:x*0.1+y,map(char2num,s[1][::-1]))/10
就是把'456'变成0.456的过程,本来想要用'456'->456再取长度L乘以0.1的L次幂,但是不懂n次幂,所以:
s[1][::-1] 把s的小数部分字符串倒着取,比如'456'变成'654'
map之后就得到 (6,5,4) 这样一个生成器
传入reduce中变成浮点数字4.56
再除以10变成我要的0.456

艰难的解出来了,但是感觉不够简洁,这道题可以聊聊啊。然后看了网站上别人的解法,发现 0.1**N这个东西应该就是0.1的N次幂,但是试了一下很尴尬:

>>> 0.1**2
0.010000000000000002
>>> 0.1*0.1
0.010000000000000002

手贱又自己试了一遍代码,这下凌乱了:

>>> s='123.456'
>>> s=s.split('.')
>>> s
['123', '456']
>>> s[1]
'456'
>>> reduce(lambda x,y:x*0.1+y,map(char2num,s[1][::-1]))/10
0.45599999999999996
#怎么会这样,我再整体打出来试试:
>>> reduce(lambda x,y:x*10+y,map(char2num,s[0]))+reduce(lambda x,y:x*0.1+y,map(char2num,s[1][::-1]))/10
123.456
#卧槽又好了,float求解释 @大佬们

另外然后想要收集一下字符串、数字等序列之间的常用处理方式和函数之类,不知哪位大佬有类似资料笔记。

ps. 王大佬思路:把s字符串去掉小数点,再转化为数字,再乘以0.1的n次幂。

from functools import reduce
def str2float(s):
    n = len(s.split('.')[1])
    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]
    return reduce(lambda x,y:x*10+y,map(char2num,s.replace('.', '')))/pow(10, n)
print('str2float(\'123.456\') =', str2float('123.456'))

过滤序列filter(function or None, iterable) --> filter object

Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

def is_odd(n):
    return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
def not_empty(s):
    return s and s.strip()
#strip()返回移除字符串头尾指定的字符生成的新字符串

list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))
# 结果: ['A', 'B', 'C']

and这句话怎么解释?
总结如下:

  1. 0、1是 False 、 True 完全等价的,可以用 0==False,注意if 'a'if 'a'==True 是不一样的
  1. 注意:
if   '' :
     print('TRUE')  

打印不了任何结果,因为'',空list ,空值和假,if都无法成立。

>>> if 'a':
...     print('TRUE')
TRUE
>>> if False:
...     print('TRUE')
>>> if []:
...     print('TRUE')
>>> if None:
...     print('TRUE')
>>> if 1:
...     print('TRUE')
TRUE
>>> if 0:
...     print('TRUE')
  1. 最后return s and s.strip()表示 判断 s and s.strip() 的布尔结果,返回True 或者 False, 当 s 和 去掉首尾空格后的s 都是真就返回True(即不是None、不是''就可以;因为此处s必须是字符串,所以不考虑s=1或0或布尔值的情况)

filter求素数 埃氏筛法

#先构造一个从3开始的无限奇数序列
def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n
#定义一个筛选函数,成倍数的都False掉
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) # 构造新序列
#调用时注意设置break
# 打印1000以内的素数:
for n in primes():
    if n < 1000:
        print(n)
    else:
        break

练习

回数

# -*- coding: utf-8 -*-
def is_palindrome(n):
     return str(n)==str(n)[::-1]
# 测试:
output = filter(is_palindrome, range(1, 1000))
print(list(output))

sorted(iterable, /, *, key=None, reverse=False)

Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

key函数对每一个元素处理后再按照ASCII的大小进行排序,返回原来的元素,reverse=True可反向排序。

练习

按成绩从高到低排序:

# -*- coding: utf-8 -*-
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_score(t):
    return t[1]
L2 = sorted(L,key=by_score,reverse=True)
print(L2)

如果要求按成绩排序,相同成绩的按姓名排序呢?
那就先按姓名排一下,排完再按成绩排一下

相关文章

网友评论

    本文标题:【python】高阶函数:map/reduce/filter/s

    本文链接:https://www.haomeiwen.com/subject/hegjattx.html