标签:ons 子集 ice log 并行运算 str open new home
基础补充1——collections模块
命名元组另一个用途就是作为字典的替代,因为字典存储需要更多的内存空间。如果你需要构建一个非常大的包含字典的数据结构,那么使用命名元组会更加高效。但 是需要注意的是,不像字典那样,一个命名元组是不可更改的。
from collections import namedtuple
records=[
(‘mac‘,2,20000),
(‘lenovo‘,1,3000),
(‘apple‘,0,10),
(‘tesla‘,10,10000000)
]
cost=0.0
for re in records:
cost+=re[1]*re[2]
print(‘商品:%s 购买个数:%s 总价:%s‘%(re[0],re[2],cost))
sk=namedtuple(‘Stock‘,[‘name‘,‘count‘,‘price‘])
for re in records:
s=sk(*re)
print(s.count,s.price)
p=namedtuple(‘People‘,[‘name‘,‘gender‘,‘age‘])
l=[‘alex‘,‘female‘,18]
p1=p(*l)
print(p1)
print(p1.name)
print(p1.gender)
print(p1.age)
#p1.name=‘karla‘#报错,不可修改
p1=p1._replace(name=‘karla‘)#需要重新赋值给p1
print(p1.name)
#重新设置一个函数,弥补只能使用_replace修改的缺点
p=namedtuple(‘People‘,[‘name‘,‘gender‘,‘age‘])
p1=p(‘‘,‘‘,None)
def dic_to_stock(s):
return p1._replace(**s)
print(dic_to_stock({‘name‘:‘karla‘,‘gender‘:‘female‘,‘age‘:18}))
print(dic_to_stock({‘name‘:‘lily‘,‘gender‘:‘male‘,‘age‘:30}))
基础补充2——从字典中提取子集
prices={
‘shiqun‘:48.78,
‘guanyuqiao‘:47.5,
‘liyijun‘:55.3,
‘zhangyaqian‘:66
}
prices_new={key:val for key,val in prices.items() if val>50}
print(prices_new)
基础补充4——带参数的装饰器
name=‘karla‘
pwd=‘root‘
def auth(auth_type):
def inner_auth(func):
def wrapper(*args,**kwargs):
username=input(‘username:‘).strip()
password=input(‘password:‘).strip()
if auth_type==‘local‘:
if username==name and password==pwd:
print(‘user login successful‘)
return func(*args,**kwargs)
else:
exit(‘log err‘)
elif auth_type==‘ldap‘:
print(‘ladp是啥呀‘)
return wrapper
return inner_auth
def index():
print(‘welcome to index page‘)
@auth(auth_type=‘local‘)
def home():
print(‘welcome to home page‘)
@auth(auth_type=‘ladp‘)
def bbs():
print(‘welcome to bbs page‘)
index()
home()
bbs()
基础补充5——生成器并行运算
import time
def consumer(name):
print(‘[%s]准备吃包子啦‘%name)
while True:
baozi=yield
print(‘包子[%s]来啦,被[%s]吃啦 ‘%(baozi,name))
def producter():
c1=consumer(‘alex‘)
c2=consumer(‘wupeiqi‘)
c1.__next__()
c2.__next__()
print(‘开始做包子啦‘)
for i in range(10):
time.sleep(1)
c1.send(i)
c2.send(i)
producter()
f=open(‘xx.log‘)
f.__next__()
标签:ons 子集 ice log 并行运算 str open new home
原文地址:https://www.cnblogs.com/qiaoqianshitou/p/9152606.html