一:列表生成式
格式:[expression for item in iterable in condition]
原代码:
l = ['alex_dsb','lxx_dsb','wxx_dsb','xxq','egon_dsb']
new_l = []
for name in l:
if name.endswith('dsb'):
new_l.append(name)
改进后:
l = ['egon_is_sb','egon_is_dsb','egon_is_superdsb','xxq','egon_dsb']
new_l = [name for name in l] # 最基础的列表生成式
new_l = [name for name in l if name.endswith('sb')]
print(new_l)
把所有小写字母变成大写
l = ['egon_is_sb','egon_is_dsb','egon_is_superdsb','xxq','egon_dsb']
new_l = [name.upper() for name in l ]
print(new_l)
去掉所有名字的_sb后缀
l = ['egon_is_sb','egon_is_sb','egon_is_superd_sb','xxq','egon_sb']
new_l = [name.replace('_sb','') for name in l]
print(new_l)
二:字典生成式
keys = ['name','age','gender']
dic = {key:None for key in keys}
print(dic)
items = [('name','egon'),('age',18),('gender','male')]
dict = {k:v for k,v in items if k!='gender'}
print(dict)
三:集合生成式
keys = ['name','age','gender']
set1 = {key for key in keys}
print(set1,type(set1))
四:元组生成式(没有元组生成式)
g = (i for i in range(10) if i > 3)
print(g,type(g))
# 输出:<generator object <genexpr> at 0x01D63450> <class 'generator'>
五:生成器表达式
g = (i for i in range(10) if i > 3)
# !!!!!!!强调!!!!!!!
# 此时g的内部,一个值都没有
# 只有next的时候,才会产生一个值
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
方式一:
with open(r'内容.txt',mode='rt',encoding='UTF-8') as f:
res = 0
for line in f:
res += len(line)
print(res)
方式二:
with open(r'内容.txt',mode='rt',encoding='UTF-8') as f:
res = sum([len(line) for line in f])
print(res)
方式三:效率高
with open(r'内容.txt', mode='rt', encoding='UTF-8') as f:
# g = (len(line) for line in f)
# print(g)
# res = sum(g)
# print(res)
# res = sum((len(line) for line in f))
# 上述可以简写为如下格式
res = sum(len(line) for line in f)
print(res)