1. 装饰器

关于Python装饰器的讲解,网上一搜有很多资料,有些资料讲的很详细。因此,我不再详述,我会给出一些连接,帮助理解。

探究functools模块wraps装饰器的用途

案例1

import functools

def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print("打印传入参数func的名字:{}".format(func.__name__))
return func(*args, **kw)
return wrapper @log
def new():
print('2018-11-24') new()
打印传入参数func的名字:new
2015-3-25

案例2

from functools import wraps   

def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Calling decorated function...')
return func(*args, **kwargs)
return wrapper @my_decorator def example():
"""Docstring"""
print('Called example function') print(example.__name__, example.__doc__)
example Docstring

案例3

def logger(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print("logger传入的参数text:{}".format(text))
print("打印传入参数func的名字:{}".format(func.__name__))
return func(*args, **kw)
return wrapper
return decorator @logger('DEBUG')
def today():
print('2018-11-24') today() print('-------------')
print(today.__name__)
logger传入的参数text:DEBUG
打印传入参数func的名字:today
2018-11-24
-------------
today

2. filter 过滤器

Python函数式编程

案例1

def is_odd(n):
return n % 2 == 1
L = range(100)
print(L)
print(list(filter(is_odd, L)))
range(0, 100)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

案例2

def not_empty(s):
return s and s.strip()
print(list(filter(not_empty, ['A', '', 'b', None, 'c', ' '])))
['A', 'b', 'c']

3. map 映射

Python函数式编程

def f(x):
return x*x
print(list(map(f, [1, 2, 3, 4, 5])))
[1, 4, 9, 16, 25]

4. partial 偏导雏形

partial具有固定参数的功能

案例1

固定say中的man参数

import functools
def say(man, words):
print('say', words, 'to', man) # say('boss', 'hello') # say hello to boss
say2boss = functools.partial(say, 'boss')
say2boss('good morning')
say good morning to boss

案例2

固定基,固定二进制,也就是将二进制函数中的基固定为2

import functools
int2 = functools.partial(int, base=2)
print('1000000 =', int2('1000000'))
print('1010101 =', int2('1010101'))
1000000 = 64
1010101 = 85

案例3

def add(a,b):
return a + b + 10
add3 = functools.partial(add,3)
add5 = functools.partial(add,5)
print("固定add函数中一个参数3,结果为3+4+10 = {} ".format(add3(4)))
print("固定add函数中一个参数5,结果为5+10+10 = {} ".format(add5(10)))
固定add函数中一个参数3,结果为3+4+10 = 17
固定add函数中一个参数5,结果为5+10+10 = 25

5. reduce

案例1

import functools
S = range(1,6)
print(functools.reduce(lambda x, y: x+y, S))
15

案例2 字符串数字转化为整型

from functools import reduce
CHAR_TO_INT = {
'0':0,
'1':1,
'2':2,
'3':3,
'4':4,
'5':5,
'6':6,
'7':7,
'8':8,
'8':9
}
def str2int(s):
ints = map(lambda ch: CHAR_TO_INT[ch], s)
return reduce(lambda x, y: x*10 + y, ints) print(str2int('0'))
print(str2int('12300'))
print(str2int('0012345'))
0
12300
12345

案例3 字符串数字转化为浮点型

CHAR_TO_FLOAT = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'.': -1
} def str2float(s):
nums = map(lambda ch: CHAR_TO_FLOAT[ch], s)
point = 0
def to_float(f, n):
nonlocal point
if n == -1:
point = 1
return f
if point == 0:
return f * 10 + n
else:
point = point * 10
return f + n / point
return reduce(to_float, nums, 0.0) print(str2float('0'))
print(str2float('123.456'))
print(str2float('123.45600'))
print(str2float('0.1234'))
print(str2float('.1234'))
print(str2float('120.0034'))
0.0
123.456
123.456
0.12340000000000001
0.12340000000000001
120.0034

6. sorted

案例1 简单排序

L = ['bob', 'about', 'Zoo', 'Credit']
print(sorted(L))
print(sorted(L, key=str.lower))
['Credit', 'Zoo', 'about', 'bob']
['about', 'bob', 'Credit', 'Zoo']

案例2 根据要求排序

from operator import itemgetter
students = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
print(sorted(students, key=itemgetter(0)))
print(sorted(students, key=lambda t: t[1]))
print(sorted(students, key=itemgetter(1), reverse=True))
[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]
[('Bart', 66), ('Bob', 75), ('Lisa', 88), ('Adam', 92)]
[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]

7. 返回函数

案例1

def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1, 2, 3, 4, 5, 6, 7, 8, 9)
print(f)
print(f())
<function lazy_sum.<locals>.sum at 0x000001C8F8CF69D8>
45

案例2

def count():
fs = []
for i in range(1, 4):
def f():
return i * i
fs.append(f)
return fs f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())
9
9
9

案例3

def count():

    fs = []

    def f(n):
def j():
return n * n
return j for i in range(1, 4):
fs.append(f(i)) return fs f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())
1
4
9

8. 素数

Python3基础-代码阅读系列—素数

def main():
for n in primes():
if n < 50:
print("{}是1——100之间的素数。".format(n))
else:
break 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) if __name__ == '__main__':
main()
2是1——100之间的素数。
3是1——100之间的素数。
5是1——100之间的素数。
7是1——100之间的素数。
11是1——100之间的素数。
13是1——100之间的素数。
17是1——100之间的素数。
19是1——100之间的素数。
23是1——100之间的素数。
29是1——100之间的素数。
31是1——100之间的素数。
37是1——100之间的素数。
41是1——100之间的素数。
43是1——100之间的素数。
47是1——100之间的素数。

参考文献

  1. http://y.tsutsumi.io/dry-principles-through-python-decorators.html
  2. http://wklken.me/posts/2013/08/18/python-extra-functools.html
  3. https://github.com/michaelliao/learn-python3/tree/master/samples/functional

Python3基础-特别函数(map filter partial reduces sorted)实例学习的更多相关文章

  1. python几个特别函数map filter reduce lambda

    lambda函数也叫匿名函数,即,函数没有具体的名称.先来看一个最简单例子: def f(x): return x**2 print f(4) Python中使用lambda的话,写成这样 g = l ...

  2. python 内置函数 map filter reduce lambda

    map(函数名,可遍历迭代的对象) # 列组元素全加 10 # map(需要做什么的函数,遍历迭代对象)函数 map()遍历序列得到一个列表,列表的序号和个数和原来一样 l = [2,3,4,5,6, ...

  3. 高阶函数-map/filter/reduce

    什么样的函数叫高阶函数: 条件:1.函数接受函数作为参数 2.函数的返回值中包含函数 高阶函数之----map函数 map(func, *iterables) --> map objectnum ...

  4. python的高阶函数(map,filter,sorted,reduce)

    高阶函数 关注公众号"轻松学编程"了解更多. 1.MapReduce MapReduce主要应用于分布式中. 大数据实际上是在15年下半年开始火起来的. 分布式思想:将一个连续的字 ...

  5. 高阶函数map(),filter(),reduce()

    接受函数作为参数,或者把函数作为结果返回的函数是高阶函数,官方叫做 Higher-order functions. map()和filter()是内置函数.在python3中,reduce()已不再是 ...

  6. Python——高阶函数——map filter zip

    一.map函数 1.作用:它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回. 2.实例 def f(x): return x* ...

  7. Python---高级函数map, filter, zip, enumerate等的用法

    今天看自然语言处理这本书的时候,被这里的高级函数的概念吸引了,因为我觉得所有的函数都只是函数而已,是为了实现特定功能而实现的,不应该有高级,低级之分啊!不过了解之后,发现这几个函数确实是有点高级,非常 ...

  8. python之内置函数:map ,filter ,reduce总结

    map函数: #处理序列中的每个元素,得到的结果是一个'列表',该列表元素个数及位置与原来一样 filter函数: #遍历序列中的每个元素,判断每个元素得到一个布尔值,如果是true,则留下来 peo ...

  9. Python3基础笔记--函数

    一.函数 定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可     特性: 1)代码重用 2)保持一致性 3)可扩展性 参考博客: Py西游攻关之 ...

随机推荐

  1. spring cloud 使用ribbon简单处理客户端负载均衡

    假如我们的multiple服务的访问量剧增,用一个服务已经无法承载, 我们可以把Hello World服务做成一个集群. 很简单,我们只需要复制Hello world服务,同时将原来的端口8762修改 ...

  2. java读取.txt文件工具类FileUtiles

    public class FileUtils { private static final String ENCODING = "UTF-8";//编码方式 /** * 获取文件的 ...

  3. python中深拷贝与浅拷贝

    # 1.浅拷贝(复制东西)a = [11,22,33] # 实际上是浅拷贝# 没有把这个变量的值赋进去,而是把另一个变量的地址拿过去了,就叫浅拷贝.b = a # print(id(a))# prin ...

  4. error: not found: value sqlContext/import sqlContext.implicits._/error: not found: value sqlContext /import sqlContext.sql/Caused by: java.net.ConnectException: Connection refused

    1.今天启动启动spark的spark-shell命令的时候报下面的错误,百度了很多,也没解决问题,最后想着是不是没有启动hadoop集群的问题 ,可是之前启动spark-shell命令是不用启动ha ...

  5. 【SpringBoot】常用注解

    @EnableAutoConfiguration 启动自动装载:使用了这个注解之后,所有引入的jar的starters都会被自动注入.这个类的设计就是为starter工作的. @RestControl ...

  6. Spring boot+CXF开发WebService Demo

    最近工作中需要用到webservice,而且结合spring boot进行开发,参照了一些网上的资料,配置过程中出现的了一些问题,于是写了这篇博客,记录一下我这次spring boot+cxf开发的w ...

  7. [BZOJ4709][JSOI2011]柠檬 决策单调性优化dp

    题解: 解法1: 单调栈优化 首先发现一个性质就是 如果当前从i转移比从j转移更加优秀 那么之后就不会从j转移 所以我们考虑利用这个性质 我们要维护一个队列保证前一个超过后一个的时间单调不减 怎么来维 ...

  8. Python_str 的内部功能介绍

    float: x.as_integer_ratio():把浮点型转换成分数最简比 x.hex():返回当前值的十六进制表示 x.fromhex():将十六进制字符串转换为浮点型 float与long的 ...

  9. keepalived当主节点切换时脚本通知 lvs

    脚本 在keepalived.conf中添加 mail  查看邮件 实验dr实验模型 给director 做主从 4台服务器 rip:192.168.0.103 rip2:192.168.0.104 ...

  10. SQL注入——SQL Injection

    本文部分内容转自:https://www.cnblogs.com/rush/archive/2011/12/31/2309203.html http://www.diybl.com/course/7_ ...