字典推导式:
data_list = ['1 hello','2 world']
result = {item.split(" ")[0]: item.split(" ")[1] for item in data_list }
print(result)
data = 'wd=搜狗&rsv_spt=1&rsv_iqid=0xd787ab5d00049167&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_dl=tb&rsv_sug3=7&rsv_sug1=6&rsv_sug7=101&rsv_sug2=0&rsv_btype=i&inputT=1988&rsv_sug4=2956'
res_list=data.split("&")
res_dic = {item.split('=')[0]:item.split("=")[1] for item in data.split("&")}
print(res_dic)
'''
字典转化为string
'''
params = {'wd': '搜狗', 'rsv_spt': '1', 'rsv_iqid': '0xd787ab5d00049167', 'issp': '1', 'f': '8', 'rsv_bp': '1', 'rsv_idx': '2', 'ie': 'utf-8',
'tn': 'baiduhome_pg', 'rsv_enter': '1', 'rsv_dl': 'tb', 'rsv_sug3': '7',
'rsv_sug1': '6', 'rsv_sug7': '101', 'rsv_sug2': '0', 'rsv_btype': 'i',
'inputT': '1988', 'rsv_sug4': '2956'}
li = []
for key,value in params.items():
# str=key+"="+value #相加效率低
str = "{}={}".format(key,value)
li.append(str)
res = "&".join(li)
print(res)
res = "&".join(["{}={}".format(key,value) for key,value in params.items()])
#集合推导式
data = {i for i in range(10)}
print(data)
闭包:函数嵌套函数,掉用外面函数 不想立即执行内容,在该函数内嵌套函数,让内部函数工作,可以在内部封装自己想要的东西
def outer(name):
def inner():
msg = "{}".format(name)
print(msg)
return inner
v = outer("Jack")
v2 = outer("Lily")
v()
v2()
线程池:
装饰器:在不改变函数的基础上 想在函数执行前后定制功能
def outer(a1):
def inner():
a1()
return inner
def x():
print("xx")
res = outer(x)
res()
@outer
def plus(v1):
return v1
res = plus(1)
print(res)
def outer(func):
def inner(*args,**kwargs):
return func(*args,**kwargs)
return inner
@outer
def plus(v1):
return v1
res = plus(1)
print(res)
"""计算一个函数的执行时间"""
import time
def coast(arg):
def inner():
start = time.time()
res = arg()
end = time.time()
print(end - start)
return res
return inner
@coast
def func():
data = 0
for i in range(10000000000):
data += i
return data
func()
def repeat_func(arg):
def inner():
result = 0
for i in range(5):
res = arg()
result += res
return result
return inner
@repeat_func
def f1():
return 123
t = f1()
print(t)
def outer(args):
def inner(a1,a2):
return args(a1,a2)
return inner
@outer
def plus(v1,v2):
return v1+v2
res = plus(1,3)
print(res)
def outer(args):
def inner(a1):
return args(a1)
return inner
@outer
def plus(v1):
return v1
res = plus(1)
print(res)
def outer(func):
def inner(*args,**kwargs):
return func(*args,**kwargs)
return inner
@outer
def plus(v1):
return v1
res = plus(1)
print(res)
"""
带参数的装饰器
"""
def tt(count):
def outer(func):
def inner(*args,**kwargs):
r = 0
for i in range(count):
res = func(*args,**kwargs)
r += res
return r
return inner
return outer
@tt(5)
def f(x):
return x
res = f(100)
print(res)
传统的装饰器是由两层嵌套,带参数的装饰器是三层。
手机扫一扫
移动阅读更方便
你可能感兴趣的文章