生成式
作者:互联网
1、列表生成式
l = ['alex_dsb', 'lxx_dsb', 'wxx_dsb', "xxq_dsb", 'egon']
new_l=[]
for name in l:
if name.endswith('dsb'):
new_l.append(name)
简化操作:
new_l=[name for name in l if name.endswith('dsb')]
2、字典生成式
keys = ['name', 'age', 'gender']
dic = {key: None for key in keys}
print(dic)
items = [('name', 'egon'), ('age', 18), ('gender', 'male')]
print(type(items))
res = {k: v for k, v in items if k != 'gender'}
print(res)
3、集合生成式
keys=['name','age','gender']
set1={key for key in keys}
print(set1,type(set1))
4、生成器表达式
g=(i for i in range(5) if i > 1) #此刻g的内部没有值!
print(next(g)) # 2
print(next(g)) # 3
print(next(g)) # 4
5、文件
with open('笔记.txt', mode='rt', encoding='utf-8') as f:
# 方式一:
res=0
for line in f:
res+=len(line)
print(res)
# 方式二: 占用内存风险
res=sum([len(line) for line in f])
print(res)
# 方式三 :效率最高
res = sum((len(line) for line in f))
# 上述可以简写为如下形式
res = sum(len(line) for line in f)
print(res)
标签:name,res,生成式,print,line,dsb 来源: https://www.cnblogs.com/bailongcaptain/p/12567271.html