1.内置参数

    Built-in Functions    
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytrarray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()  

内置参数详解 https://docs.python.org/3/library/functions.html?highlight=built#ascii

2.迭代器&生成器

列表生成式,是Python内置的一种极其强大的生成list的表达式。

如果要生成一个list [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9] 可以用 range(1 , 10):

1
2
#print(list(range(1,10)))
[123456789]

如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?

1
2
3
4
5
6
= []
for in range(1,10):
    l.append(i*i)
print(l)
####打印输出####
#[1, 4, 9, 16, 25, 36, 49, 64, 81]

而列表生成式则可以用一行语句代替循环生成上面的list:

1
2
>>> print([x*for in range(1,10)])
[149162536496481]

for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:

1
2
>>> print([x*for in range(1,10if %2 ==0])
[4163664]
  1. >>>[ i*2 for i in range(10)]
  2. [0,1,4,6,8,10,12,14,16,18]
  3. 等于
  4. >>>a=[]
  5. >>>for i in range(10):
  6. . . . a.append(i*2)
  7. >>>a
  8. [0,1,4,6,8,10,12,14,16,18]

小程序

  1. str1 = ""
  2. for i in iter(input,""): # 循环接收 input输入的内容
  3. str1 += i
  4.  
  5. print(str1)

生成器

通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。

所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。

要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:

  1. >>>l = [x*x for x in range(10)]
  2. >>>l
  3. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  4. >>>g = (x*x for x in range(10))
  5. >>>g
  6. <generator object <genexpr> at 0x1022ef630>

创建Lg的区别仅在于最外层的[]()L是一个list,而g是一个generator。

我们可以直接打印出list的每一个元素,但我们怎么打印出generator的每一个元素呢?

如果要一个一个打印出来,可以通过next()函数获得generator的下一个返回值:

  1. >>> next(g)
  2. 0
  3. >>> next(g)
  4. 1
  5. >>> next(g)
  6. 4
  7. >>> next(g)
  8. 9
  9. >>> next(g)
  10. 16
  11. >>> next(g)
  12. 25
  13. >>> next(g)
  14. 36
  15. >>> next(g)
  16. 49
  17. >>> next(g)
  18. 64
  19. >>> next(g)
  20. 81
  21. >>> next(g)
  22. Traceback (most recent call last):
  23. File "<stdin>", line 1, in <module>
  24. StopIteration

所以,我们创建了一个generator后,基本上永远不会调用next(),而是通过for循环来迭代它,并且不需要关心StopIteration的错误。

generator非常强大。如果推算的算法比较复杂,用类似列表生成式的for循环无法实现的时候,还可以用函数来实现。

比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

  

  1. def fib(max):
  2. n,a,b=0,0,1
  3. while n < max:
  4. print(b)
  5. a,b=b,a+b
  6. n = n+1
  7. return 'done'

上面的函数可以输出斐波那契数列的前N个数:

  1. >>>fib(10)
  2. 1
  3. 1
  4. 2
  5. 3
  6. 5
  7. 8
  8. 13
  9. 21
  10. 34
  11. 55
  12. done

生成器的特点:

1)生成器只有在调用时才会生成相应的数据;

2)只记录当前位置;

3)只有一个__next__()方法;

还可通过yield实现在单线程的情况下实现并发运算的效果:

  1. import time
  2. def consumer(name):
  3. print("%s 准备吃包子!" %name)
  4. while True:
  5. baozi = yield
  6. print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
  7. c = consumer("ChenRonghua")
  8. c.__next__()
  9.  
  10. def produceer(name):
  11. c = consumer("a")
  12. c2 = consumer("b")
  13. c.__next__()
  14. c2.__next__()
  15. print("老子开始准备做包子啦!")
  16. for i in range(10):
  17. time.sleep(1)
  18. print("做了1个包子,分两半!")
  19. c.send(i)
  20. c2.send(i)
  21. produceer("alex")

  迭代器

我们已经知道,可以直接作用于for循环的数据类型有以下几种:

一类是集合数据类型,如listtupledictsetstr等;

一类是generator,包括生成器和带yield的generator function。

这些可以直接作用于for循环的对象统称为可迭代对象:Iterable

可以使用isinstance()判断一个对象是否是Iterable对象:

  1. >>>from collections import Iterable
  2. >>>isinstance([],Iterable)
  3. True
  4. >>>isinstance({},Iterable)
  5. True
  6. >>>isinstance('abc',Iterable)
  7. True
  8. >>> isinstance((x for x in range(10)), Iterable)
  9. True
  10. >>> isinstance(100, Iterable)
  11. False

  

凡是可作用于for循环的对象都是Iterable类型;

凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;

集合数据类型如listdictstr等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。

Python的for循环本质上就是通过不断调用next()函数实现的,例如:

  1. for x in [1,2,3,4,5]:
  2. pass

实际上完全等价于:

  1. # 首先获得Iterator对象:
  2. it = iter([1, 2, 3, 4, 5])
  3. # 循环:
  4. while True:
  5. try:
  6. # 获得下一个值:
  7. x = next(it)
  8. except StopIteration:
  9. # 遇到StopIteration就退出循环
  10. break

  

3.Json&pickle数据序列化

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

  1. info = {
  2. "name":"alex",
  3. "age":22
  4. }
  5. f = open("test.txt","w")
  6. f.write(info)
  7. f.close()

json序列化

  1. f = open("test.txt","r")
  2.  
  3. data = eval(f.read())
  4. f.close()
  5. print(data['age'])

json反序列化

json能处理简单的数据类型,字典,列表,字符串。

json是所有语言通用的,json的作用是不同语言之间进行数据交互。

  1. #json序列化
  2. import json
  3. info = {
  4. "name":"alex",
  5. "age":22
  6. }
  7. f = open("test.txt","w")
  8. #print(json.dumps(info))
  9. f.write(json.dumps(info))
  10. f.close()
  11. #json反序列化
  12. import json
  13. f = open("test.txt","r")
  14.  
  15. data = json.loads(f.read())
  16. f.close()
  17. print(data['age'])

json序列化,反序列化

  1. import pickle
  2. def sayhi(name):
  3. print("hello,",name)
  4. info = {
  5. "name":"alex",
  6. "age":22,
  7. "func":sayhi
  8. }
  9. f = open("test.txt","wb")
  10.  
  11. f.write(pickle.dumps(info))
  12. f.close()

pickle序列化

  1. import pickle
  2. def sayhi(name):
  3. print("hello,",name)
  4. f = open("test.txt","rb")
  5. data = pickle.loads(f.read())
  6.  
  7. print(data['func']("Alex"))

pickle反序列化

4.装饰器

定义:

本质上是个函数,功能是装饰其他函数—就是为其他函数添加附加功能

装饰器原则:

1)  不能修改被装饰函数的源代码;

2)  不能修改被装饰函数的调用方式;

实现装饰器知识储备:

函数即“变量”

定义一个函数相当于把函数体赋值给了函数名

1.函数调用顺序:其他高级语言类似,python不允许在函数未声明之前,对其进行引用或者调用

错误示范:

  1. def foo():
  2. print('in the foo')
  3. bar()
  4. foo()
  5.  
  6. 报错:
  7. in the foo
  8. Traceback (most recent call last):
  9. File "<pyshell#13>", line 1, in <module>
  10. foo()
  11. File "<pyshell#12>", line 3, in foo
  12. bar()
  13. NameError: global name 'bar' is not defined
  14.  
  15. def foo():
  16. print('foo')
  17. bar()
  18. foo()
  19. def bar()
  20. print('bar')
  21. 报错:NameError: global name 'bar' is not defined

正确示范:(注意,python为解释执行,函数foo在调用前已经声明了bar和foo,所以bar和foo无顺序之分)

  1. def foo()
  2. print('in the foo')
  3. bar()
  4. def bar():
  5. print('in the bar')
  6. foo()
  7.  
  8. def bar():
  9. print('in the bar')
  10. def foo():
  11. print('in the foo')
  12. bar()
  13. foo()

2.高阶函数

满足下列条件之一就可成函数为高阶函数

  1.某一函数当做参数传入另一个函数中

  2.函数的返回值包含n个函数,n>0

高阶函数示范:

  1. def bar():
  2. print('in the bar')
  3. def foo(func):
  4. res=func()
  5. return res
  6. foo(bar)

高阶函数的牛逼之处:

  1. def foo(func):
  2. return func
  3. print('function body is %s' %(foo(bar)))
  4. print('function name is %s' %(foo(bar).func_name))
  5. foo(bar)()
  6. #foo(bar)() 等同于bar=foo(bar)然后bar()
  7. bar = foo(bar)
  8. bar()

3.内嵌函数和变量作用域

定义:在一个函数体内创建另一个函数,这种函数就叫内嵌函数

嵌套函数:

  1. def foo():
  2. def bar():
  3. print('in the bar')
  4. bar()
  5. foo()

局部作用域和全局做用域的访问顺序

  1. x = 0
  2. def grandpa():
  3. def dad():
  4. x = 2
  5. def son():
  6. x=3
  7. print(x)
  8. son()
  9. dad()
  10. grandpa()

4.高阶函数+内嵌函数=》装饰器

函数参数固定

  1. def decorartor(func):
  2. def wrapper(n):
  3. print('starting')
  4. func(n)
  5. print('stopping')
  6. return wrapper
  7.  
  8. def test(n):
  9. print('in the test arg is %s' %n)
  10. decorartor(test)('alex')

函数参数不固定

  1. def decorartor(func):
  2. def wrapper(*args,**kwargs):
  3. print('starting')
  4. func(*args,**kwargs)
  5. print('stopping')
  6. return wrapper
  7.  
  8. def test(n,x=1):
  9. print('in the test arg is %s' %n)
  10. decorartor(test)('alex',x=2222)

1.无参装饰器

  1. import time
  2. def decorator(func):
  3. def wrapper(*args,**kwargs):
  4. start_time=time.time()
  5. func(*args,**kwargs)
  6. stop_time=time.time()
  7. print("%s" %(stop_time-start_time))
  8. return wrapper
  9.  
  10. @decorator
  11. def test(list_test):
  12. for i in list_test:
  13. time.sleep(0.1)
  14. print('-'*20,i)
  15.  
  16. #decorator(test)(range(10))
  17. test(range(10))

2.有参装饰器

  1. import time
  2. def timer(timeout=0):
  3. def decorator(func):
  4. def wrapper(*args,**kwargs):
  5. start=time.time()
  6. func(*args,**kwargs)
  7. stop=time.time()
  8. print('run time is %s ' %(stop-start))
  9. print(timeout)
  10. return wrapper
  11. return decorator
  12. @timer(2)
  13. def test(list_test):
  14. for i in list_test:
  15. time.sleep(0.1)
  16. print ('-'*20,i)
  17.  
  18. #timer(timeout=10)(test)(range(10))
  19. test(range(10))

3.终极装饰器

  1. user,passwd = 'alex','abc123'
  2. def auth(auth_type):
  3. print('auth func:',auth_type)
  4. def outer_wrapper(func):
  5. def wrapper(*args,**kwargs):
  6. print("wrapper func args:",*args,**kwargs)
  7. if auth_type=="local":
  8. username = input("Username:").strip()
  9. password = input("Password:").strip()
  10. if user == username and passwd == password:
  11. res = func(*args,**kwargs)
  12. print("---after authentication")
  13. return res
  14. else:
  15. exit("\033[31;1mInvalid username or password\033[0m")
  16. elif auth_type == "ldap":
  17. print('搞毛线ldap,不会......')
  18.  
  19. return wrapper
  20. return outer_wrapper
  21.  
  22. def index():
  23. print("welcome to index page")
  24. @auth(auth_type="local") #home = wrapper()
  25. def home():
  26. print("welcome to home page")
  27. return "from home"
  28. @auth(auth_type="ldap")
  29. def bbs():
  30. print("welcome to bbs page")
  31.  
  32. index()
  33. print(home())#wrapper()
  34. bbs()

Python 迭代器&生成器的更多相关文章

  1. Python迭代器生成器与生成式

    Python迭代器生成器与生成式 什么是迭代 迭代是重复反馈过程的活动,其目的通常是为了逼近所需目标或结果.每一次对过程的重复称为一次"迭代",而每一次迭代得到的结果会作为下一次迭 ...

  2. python 迭代器 生成器

    迭代器 生成器 一 什么是迭代器协议 1.迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代 (只能往后走不能往前 ...

  3. Python 迭代器&生成器,装饰器,递归,算法基础:二分查找、二维数组转换,正则表达式,作业:计算器开发

    本节大纲 迭代器&生成器 装饰器  基本装饰器 多参数装饰器 递归 算法基础:二分查找.二维数组转换 正则表达式 常用模块学习 作业:计算器开发 实现加减乘除及拓号优先级解析 用户输入 1 - ...

  4. python迭代器,生成器,推导式

    可迭代对象 字面意思分析:可以重复的迭代的实实在在的东西. list,dict(keys(),values(),items()),tuple,str,set,range, 文件句柄(待定) 专业角度: ...

  5. 4.python迭代器生成器装饰器

    容器(container) 容器是一种把多个元素组织在一起的数据结构,容器中的元素可以逐个地迭代获取,可以用in, not in关键字判断元素是否包含在容器中.通常这类数据结构把所有的元素存储在内存中 ...

  6. python迭代器生成器

    1.生成器和迭代器.含有yield的特殊函数为生成器.可以被for循环的称之为可以迭代的.而可以通过_next()_调用,并且可以不断返回值的称之为迭代器 2.yield简单的生成器 #迭代器简单的使 ...

  7. Python迭代器生成器,私有变量及列表字典集合推导式(二)

    1 python自省机制 这个是python一大特性,自省就是面向对象的语言所写的程序在运行时,能知道对象的类型,换句话说就是在运行时能获取对象的类型,比如通过 type(),dir(),getatt ...

  8. Python迭代器生成器,模块和包

      1.迭代器和生成器 2.模块和包 1.迭代器 迭代器对象要求支持迭代器协议的对象,在Python中,支持迭代器协议就是实现对象的__iter__()和__next__()方法.    其中__it ...

  9. python迭代器生成器-迭代器和list区别

    迭代 生成 for循环遍历的原理 for循环遍历的原理就是迭代,in后面必须是可迭代对象 为什么要有迭代器 对于序列类型:字符串.列表.元组,我们可以使用索引的方式迭代取出其包含的元素.但对于字典.集 ...

随机推荐

  1. BZOJ1110: [POI2007]砝码Odw

    Description 在byteotian公司搬家的时候,他们发现他们的大量的精密砝码的搬运是一件恼人的工作.公司有一些固定容量的容器可以装这些砝码.他们想装尽量多的砝码以便搬运,并且丢弃剩下的砝码 ...

  2. Solr资料

    Apache Solr Reference GuideCovering Apache Solr 5.5 https://archive.apache.org/dist/lucene/solr/ref- ...

  3. js根据浏览器窗口大小实时改变网页文字大小

    目前,有了css3的rem,给我们的移动端开发带来了前所未有的改变,使得我们的开发更容易,更易兼容很多设备,但这个不在本文讨论的重点中,本文重点说说如何使用js来实时改变网页文字的大小. 代码: &l ...

  4. [CareerCup] 18.4 Count Number of Two 统计数字2的个数

    18.4 Write a method to count the number of 2s between 0 and n. 这道题给了我们一个整数n,让我们求[0,n]区间内所有2出现的个数,比如如 ...

  5. [CareerCup] 15.7 Student Grade 学生成绩

    15.7 Imagine a simple database storing information for students' grades. Design what this database m ...

  6. java.lang.String

    1.String 是一个类,广泛应用于 Java 程序中,相当于一系列的字符串.在 Java 语言中 strings are objects.创建一个 strings 最直接的方式是 String g ...

  7. 伪类link,hover,active,visited,focus的区别

    例一: /*css*/a:link{  color: blue;}a:visited{  color: green;}a:hover{  color: red;}a:focus{ color:blac ...

  8. jq最新前三篇文章高亮显示

    /*---------最新前三篇文章高亮显示-------------*/ function latest(){ var color_arr=new Array( "blue", ...

  9. Jquery dialog属性

    修改标题: $('#test').dialog("option","title", "测试").dialog('open'); 修改位置: ...

  10. BizTalk开发系列(十五) Schema设计之Qualified 与Unqualified

    XML Schema中的命名空间前缀限定包括对元素(Element)或属性(Attribute)的限定,即常见的如 “<ns0:root>...</ns0:root>”之类的格 ...