Python 高级进阶
6-22日
1.推导式
[x*y for x in range(1,6) if x > 2 for y in range(1,7) if y < 3]
#他的执行顺序是:
for x in range(1,6):
if x > 2:
for y in range(1,7):
if y < 3:
x*y
#1-1
names = ['Joe','Bill','Jefferson','Andy','Wesley','Keven','Tom', 'Alice','Jill','Ana','Wendy','Jenny','Sherry','Eva']
list_=[]
for i in names:
if len(i)>4:
list_.append(i)
print(list_)
print([i for i in names if len(i)>4])
#1-2
print([i.upper() if len(i)>5 else i for i in names ])
list_ = []
for i in names:
if len(i)>5:
list_.append(i.upper())
#2
print([i for i in range(1,11) if i % 2 == 0])
#range()
rg = range(5)
print(rg)
print(list(rg))
# range(start, stop[, step]),range是一种生成器
# lst和range都是可迭代对象
['Jefferson', 'Wesley', 'Keven', 'Alice', 'Wendy', 'Jenny', 'Sherry']
['Jefferson', 'Wesley', 'Keven', 'Alice', 'Wendy', 'Jenny', 'Sherry']
['Joe', 'Bill', 'JEFFERSON', 'Andy', 'WESLEY', 'Keven', 'Tom', 'Alice', 'Jill', 'Ana', 'Wendy', 'Jenny', 'SHERRY', 'Eva']
[2, 4, 6, 8, 10]
range(0, 5)
[0, 1, 2, 3, 4]
2.zip拉练操作
x = [[1], 2, 3, 4, 5]
y = ['a', 'b', 'c', 'd', 'e','f']
z = ['a1', 'b2', 'c3', 'd4', 'e5']
for a,b,c in zip(x,y,z):
print(f"{a}-->{b}-->{c}")
#等同于:
for i in range(len(x)):
print(f"{x[i]}-->{y[i]}-->{z[i]}")
[
1]-->a-->a1
2-->b-->b2
3-->c-->c3
4-->d-->d4
5-->e-->e5
[1]-->a-->a1
2-->b-->b2
3-->c-->c3
4-->d-->d4
5-->e-->e5
3.拉平嵌套
from itertools import chain
li=[[1,2],[3,4],[5,6]]
print(list(chain.from_iterable(li)))
t=[]
[t.extend(i) for i in li]
print(t)
cost1 0.04690122604370117
cost2 0.041800737380981445
cost3 0.05563974380493164
**
chain的时间比较
**
#encoding=utf8
import time
from itertools import chain
li=[[1,2],[3,4],[5,6]] *100000#[1,2,3,4,5,6]
t=time.time()
l=list(chain.from_iterable(li))
print(f"cost1 {time.time()-t}")
t=time.time()
l=list(chain(*li))
print(f"cost2 {time.time()-t}")
t1=time.time()
t=[]
[t.extend(i) for i in li]
print(f"cost3 {time.time()-t1}")
#print(t)
4.避免过多循环
a d m
a d n
a e m
a e n
a f m
a f n
b d m
b d n
b e m
b e n
b f m
b f n
c d m
c d n
c e m
c e n
c f m
c f n
等同于:
a d m
a d n
a e m
a e n
a f m
a f n
b d m
b d n
b e m
b e n
b f m
b f n
c d m
c d n
c e m
c e n
c f m
c f n
5.高阶函数
6.匿名函数
7.偏函数
functools.par tial冻结参数
from functools import partial
def add(a,b,c,d):
return a+b+c+d
triple = partial(add, 3,2)
l=triple(1,7)
print(l)
13
8.装饰器
装饰器是可调用的对象,其参数是另一个函数。
装饰器的作用:增强被装饰函数,改变被装饰函数的行为。
```bash
r=[]
def reg(func):
print(f"running register {func} ")
r.append(func)
return func
#reg(f1)
@reg
def f1():
print("running f1()")
f1 = reg(f1)#-->f1=f1
f1()#f1()
def main():
f1()
if __name__=="__main__":
main()
9.闭包
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210622170224292.png)
```bash
import time
"""
闭包
"""
def outer_func():
loc_list=[]
name='zhangsan'
age=10
m=[1,2]
def inner_func(name):
nonlocal age
age+=1
m.append(len(loc_list))
s=sum(m)
loc_list.append(len(loc_list)+1)
print(f"{name} loc_list={loc_list} ,sum of m {s},age is {age}")
return inner_func
#o=outer_func()
close = outer_func()
close("f0") #1
close("f0") #2
close1 = outer_func()
close("f0") #3
close("f0") #4
close1("f1") #1
close1("f1") #2
f0 loc_list=[1] ,sum of m 3,age is 11
f0 loc_list=[1, 2] ,sum of m 4,age is 12
f0 loc_list=[1, 2, 3] ,sum of m 6,age is 13
f0 loc_list=[1, 2, 3, 4] ,sum of m 9,age is 14
f1 loc_list=[1] ,sum of m 3,age is 11
f1 loc_list=[1, 2] ,sum of m 4,age is 12
10.装饰器+闭包
def deco(func):
def inner():
print('running inner()')
return inner
@deco
def target():
print('running target()')
#target = deco(target)#-->target = inner
target()# --->inner()
"""
在定义被装饰函数时发生的事情:
target = deco(target)
在调用被装饰函数时,即target(),发生的事情是:
deco(target)()
也就是inner()
"""
"""
那装饰器返回的函数除了是自己内部定义的函数,可以是外部的函数吗?
可以,但是注意要在定义装饰器之前定义。
"""
def deco(func):
func()
return my_print
def my_print():
print("executing my_print..")
@deco
def func1():
print("executing func1")
func1 = deco(func1)#-->func1 = my_print
func1()#--->my_print()
running inner()
executing func1
executing my_print..
executing my_print..