Python学习day4
一、迭代器&生成器
1. 列表[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],要求你把列表里的每个值加1,有以下几种方法:
(1)a = [1,3,4,6,7,7,8,9,11]
for index,i in enumerate(a):
a[index] +=1
print(a)
(2) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a = map(lambda x:x+1, a)
(3)a = [i+1 for i in range(10)]
2.斐波那契数列
def fib(max):
n,a,b = 0,0,1
while n < max:
yield b
a,b, = b,a+b
n += 1
return 'done'
f = fib(10)
print(f.__next__())
print("======")
for i in f:
print(i)
二、装饰器
1.
#定义:本质是函数,为其他函数添加附加功能
#原则:1.不能修改被装饰的函数的源代码
# 2.不能修改被装饰的函数的调用方式
# 知识储备:
# 1.函数即变量
# 2.高阶函数
# a:吧一个函数名当做实参传给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
# b:换回值中包含函数名(不能修改函数的调用方式)
# 3.嵌套函数
import time
def timmer(func):
def warpper(*args,**kwargs):
start_time = time.time()
func()
stop_time = time.time()
print('the func run time is %s' %(stop_time - start_time))
return warpper()
@timmer
def test1():
time.sleep(3)
print("in the test1")
test1()
2.import time
# def bar():
# time.sleep(2)
# print('in the bar')
#
# def test1(func):
# start_time = time.time()
# func() #run bar
# stop_time = time.time()
# print("the func run time is %s" %(stop_time - start_time))
#
# test1(bar)
def bar():
time.sleep(2)
print('in the bar')
def test2(func):
print(func)
return func
#print(test2(bar))
bar = test2(bar)
bar()
3.#嵌套函数
def foo():
print('in the foo')
def bar():
print('in the bar')
bar()
foo()
4.import time
def timer(func):
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print("%s" %(stop_time - start_time))
return deco
@timer #相当于test1 = timer(test1),在需要添加功能的函数上加上
def test1():
time.sleep(1)
print('int the test1')
@timer #test2 = timer(test2) = deco test2(name) = deco(name)
def test2(name,age):
print('in the test2:',name,age)
test1()
test2("alex",22)
5. 高级版装饰器
import time
user,passwd = 'alex','abc123'
def auth(func):
def wrapper(*args,**kwargs):
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args,**kwargs)
print("---")
return res
else:
exit("\033[32;1mInvalid input\033[0m")
return wrapper
def index():
print("welcome to index page")
@auth
def home():
print("welcome to home page")
return "from home"
@auth
def bbs():
print("welcome to bbs page")
index()
print(home())
bbs()
6. 生成器并行
import time
def consumer(name):
print("%s 准备吃包子啦!" %name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
def producer(name):
c = consumer('A')
c2 = consumer('B')
c.__next__() #必须next一下
c2.__next__()
print("老子开始准备做包子啦!")
for i in range(10):
time.sleep(1)
print("做了1个包子!")
c.send(i)
c2.send(i)
producer("alex")
三、Json & pickle 数据序列化
1.json序列化1
#import json
import pickle
def sayhi(name):
print("hello",name)
info = {
'name':'alex',
'age':22,
'func':sayhi
}
f = open("test.txt","wb")
#print(json.dumps(info))
#f.write(json.dumps(info))#序列化用dumps
f.write(pickle.dumps(info))
f.close()
2. json反序列化1
#import json
import pickle
def sayhi(name):
print("hello2",name)
f = open("test.txt","rb")
data = pickle.loads(f.read())#反序列化用loads
print(data["age"])
3. json序列化2
import pickle
def sayhi(name):
print("hello",name)
info = {
'name':'alex',
'age':22,
'func':sayhi
}
f = open("test.test","wb")
pickle.dump(info,f) #f.write(pickle.dumps(info))
f.close()
4. json反序列化2
import pickle
def sayhi(name):
print("hello2",name)
f = open("test.txt","rb")
data = pickle.load(f)#data = pickle.loads(f.read())#反序列化用loads
print(data["age"])
四、内置方法大全
#abs()#取绝对值
#all
# 回归True如果可迭代是真(或者如果迭代是空的)
# print(all([1,-5,3]))
# any(可迭代)
# 回归True如果可迭代是真的。如果可迭代为空,则返回False
# print(any([0,1]))
# bin(x)
# 将整数转换为以“0b”为前缀的二进制字符串
# a = bytes("abcde",encoding="utf-8")
# b = bytearray("abcde",encoding="utf-8")
# print(b[1])
# b[1] = 50
# print(b)
#判断这个函数是否能调用
# def sayhi(): pass
# print(callable(sayhi))
#chr(98)把字符转换成ASKII码
#ord('b)反过来
#(lambda n:print(n))(5) 匿名函数传参
# calc = lambda n:print(n**n) #lambda只能处理三元运算,复杂的处理不了了
# calc(5)
#filter:过滤出你想要的
# fil = filter(lambda n:n>5,range(10))
# for i in fil:
# print(i)
#map:对每个值都处理
# res = map(lambda n:n*n,range(10))
# for i in res:
# print(i)
# import functools
# res = functools.reduce(lambda x,y:x+y,range(10))#累加
# print(res)
#frozenset不可变的列表
#a = frozenset([1,2,44])
#打印所有变量,字典方式
#print(globals())
#hex()#变成16进制
#print(hex(255))
#locals()只有local里面有局部变量
# def test():
# local_var = 333
# print(locals())
# test()
# print(globals())
# print(globals().get('local_var'))
#oct返回8进制
#pow a的b次方
#print(pow(2,3))
#round保留小数点
#sorted
# a = {6:2,8:0,1:4,-5:6,99:11,4:22}
# print(sorted(a.items(),key = lambda x:x[1])) #列表排序出来,key = lambda x:x[1])是按照value排序
# print(a)
#zip拼接函数
# a = [1,2,3,4]
# b = ['a','b','c','d']
# zz = zip(a,b)
# for i in zz:
# print(i)

浙公网安备 33010602011771号