from contextlib import contextmanager
'''生成器推导式应用'''
in_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7]
print('array before:', in_list)
array = (i for i in in_list if i % 2 != 0) # 生成器推导表达式
print('array after:', array)
num = 3
while num > 0:
print(next(array))
num -= 1
'''集合推导式应用'''
arrayset = {i for i in in_list if i % 2 != 0} # 集合推导表达式
print('array after:', arrayset)
'''字典推导式应用,默认执行字典中的key'''
in_dict = {1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9"}
arraydict = (i for i in in_dict if i % 2 != 0)
print('array after:', arraydict)
num = 3
while num > 0:
print(next(arraydict))
num -= 1
'''python函数中的动态参数'''
def dynamic(*args, **kwargs):
print(args)
print(**kwargs)
'''python中的else语句'''
#python中的循环语句使用else意义在于,若循环非正常结束,则执行else,否则不执行
#关注的是是否完成操作流程,而不是操作的结果
#正确该做什么事,不正确该做什么事
def forelse():
#若循环成功执行则执行else语句
for i in range(10):
if i > 12:
print(i)
else:
print("over")
def tryelse():
try:
with open(r'D:\\1.txt','r') as rd:
rd.write('io')
except: #若出错则执行except
print('error')
else: #若成功执行则执行else
print('else')
finally: #不管成功还是不成功都执行finally
print("finally")
def whileelse():
num =3
while num > 5:
print(num)
else:
print('else')
'''python中的上下文管理器:上下文管理器就是一个可控流程,相当于对流程的封装,只需关注流程应该做的事'''
#方法一:使用__enter__与__exit__协议实现
#方法二:使用contextmanager与函数yield实现
class Myclass(object):
def __init__(self, file_name, mode):
self.file_name = file_name
self.mode = mode
def __enter__(self):
print("entering context management")
self.file = open(self.file_name, self.mode)
return self.file
def __exit__(self, *args, **kwargs):
print("exiting context management")
self.file.writelines('text finished!')
self.file.close()
@contextmanager
def context_generater(file_name, mode):
print("context generater entering")
file = open(file_name, mode)
yield file #yield之前相当于__enter__ yield之后相当于__exit__
print('context generater exiting')
file.writelines('context generater exiting')
file.close()
if __name__ == "__main__":
dynamic(in_list, in_dict)
forelse()
tryelse()
whileelse()
#上下文管理方式一
with Myclass(r'D:\Project related\test.txt', 'w') as f1:
f1.writelines("enter and exit start")
#上下文管理方式二
with context_generater(r'D:\Project related\test.txt', 'w+') as f2:
f2.writelines('context generater start')