Python学习笔记一
tags:
- python入门
- map, reduce, filter
Python学习笔记一
>>> f = abs
>>> f
<built-in function abs>
结论:python函数本身也可以赋值给变量,即:变量可以指向函数。
如果一个函数赋给一个变量,那么这个变量可以指向函数:
>>> f = abs
>>> f(-10)
10
成功!说明f变量现在已经指向abs函数本身。直接调用abs()函数和调用变量f()完全相同。
函数名也是变量:
那么函数名其实就是指向函数的变量,对于abs()这个函数,完全可以吧函数名abs看成变量,它指向一个可以计算绝对值的函数!如果把abs指向其他对象,会发生什么情况?
>>> abs = 10
>>> abs(-10)
>Traceback (most recent call last):
>File 'stdin', line 1, in <module>
>TypeError: 'int' object is not callable
把abs指向10后,就无法通过abs(-10)调用该函数了,因为abs这个变量已经不指向求绝对值函数而是指向一个整数10!当然实际代码绝对不能这样写,要恢复abs函数,请重启Python交互环境。
注:由于abs函数实际上是定义在import builtins模块中的,所以要让修改abs变量的指向在其它模块也生效,要用import builtins; builtins.abs = 10。
传入函数:
既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
一个最简单的高阶函数:
def add(x, y, f):
return f(x) + f(y)
当我们调用add(-5, 6, abs)时,参数x,y和f分别接收-5,6和abs,根据函数定义,我们可以推导计算过程为:
x = -5
y = 6
f = abs
f(x) + f(y) ==> abs(-5) + abs(6) ==> 11
return 11
用代码验证一下:
>>> add(-5, 6, abs)
11
编写高阶函数,就是让函数的参数能够接收别的函数。
小结:
把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。
map/reduce:
map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
练习:
- 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:[‘adam’, ‘LISA’, ‘barT’],输出:[‘Adam’, ‘Lisa’, ‘Bart’]:
# -*- coding: utf-8 -*-
def normalize(name):
return name[0].upper()+name[1:].lower()
2.Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:
# -*- coding: utf-8 -*-
from functools import reduce
def prod(L):
def f(x, y):
return x * y
return reduce(f, L)
3.利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456:
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
left, right = s.split('.')
t = len(right)
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]
def fn(x,y):
return 10*x+y
L1 = reduce(fn, map(char2num, left))
L2 = reduce(fn, map(char2num, right)) / pow(10, t)
return L1+L2
filter:Python内建的filter()函数用于过滤序列。
和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
结果: [1, 5, 9, 15]
练习:
1.回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()滤掉非回数:
# -*- coding: utf-8 -*-
def is_palindrome(n):
s = str(n)
length = len(s)
t = int(length / 2)
index = 0
while t >= 0:
if s[index] != s[length - 1 - index]:
return 0
t = t - 1
index = index + 1
return 1
#测试:
output = filter(is_palindrome, range(1, 1000))
print(list(output))
基本思路:
输入数字转成字符串str(),然后反转[::-1],再变成整数int()与原输入数字比较。两者相等则是回数,反之不是。
源码:
# -*- coding: utf-8 -*-
def is_palindrome(n):
return int(str(n)[::-1]) == n
# 测试:
output = filter(is_palindrome, range(1, 1000))
print(list(output))
>>> f = abs
>>> f
<built-in function abs>
结论:python函数本身也可以赋值给变量,即:变量可以指向函数。
如果一个函数赋给一个变量,那么这个变量可以指向函数:
>>> f = abs
>>> f(-10)
10
成功!说明f变量现在已经指向abs函数本身。直接调用abs()函数和调用变量f()完全相同。
函数名也是变量:
那么函数名其实就是指向函数的变量,对于abs()这个函数,完全可以吧函数名abs看成变量,它指向一个可以计算绝对值的函数!如果把abs指向其他对象,会发生什么情况?
>>> abs = 10
>>> abs(-10)
>Traceback (most recent call last):
>File 'stdin', line 1, in <module>
>TypeError: 'int' object is not callable
把abs指向10后,就无法通过abs(-10)调用该函数了,因为abs这个变量已经不指向求绝对值函数而是指向一个整数10!当然实际代码绝对不能这样写,要恢复abs函数,请重启Python交互环境。
注:由于abs函数实际上是定义在import builtins模块中的,所以要让修改abs变量的指向在其它模块也生效,要用import builtins; builtins.abs = 10。
传入函数:
既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
一个最简单的高阶函数:
def add(x, y, f):
return f(x) + f(y)
当我们调用add(-5, 6, abs)时,参数x,y和f分别接收-5,6和abs,根据函数定义,我们可以推导计算过程为:
x = -5
y = 6
f = abs
f(x) + f(y) ==> abs(-5) + abs(6) ==> 11
return 11
用代码验证一下:
>>> add(-5, 6, abs)
11
编写高阶函数,就是让函数的参数能够接收别的函数。
小结:
把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。
map/reduce:
map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
练习:
- 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:[‘adam’, ‘LISA’, ‘barT’],输出:[‘Adam’, ‘Lisa’, ‘Bart’]:
# -*- coding: utf-8 -*-
def normalize(name):
return name[0].upper()+name[1:].lower()
2.Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:
# -*- coding: utf-8 -*-
from functools import reduce
def prod(L):
def f(x, y):
return x * y
return reduce(f, L)
3.利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456:
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
left, right = s.split('.')
t = len(right)
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]
def fn(x,y):
return 10*x+y
L1 = reduce(fn, map(char2num, left))
L2 = reduce(fn, map(char2num, right)) / pow(10, t)
return L1+L2
filter : Python内建的filter()函数用于过滤序列。
和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
结果: [1, 5, 9, 15]
练习:
1.回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()滤掉非回数:
方法一:
# -*- coding: utf-8 -*-
def is_palindrome(n):
s = str(n)
length = len(s)
t = int(length / 2)
index = 0
while t >= 0:
if s[index] != s[length - 1 - index]:
return 0
t = t - 1
index = index + 1
return 1
#测试:
output = filter(is_palindrome, range(1, 1000))
print(list(output))
方法二:
基本思路: 输入数字转成字符串str(),然后反转[::-1],再变成整数int()与原输入数字比较。两者相等则是回数,反之不是。
# -*- coding: utf-8 -*-
def is_palindrome(n):
return int(str(n)[::-1]) == n
# 测试:
output = filter(is_palindrome, range(1, 1000))
print(list(output))