目录
三元表达式与生成式
1 三元表达式
1.1 三元表达式的定义
三元表达式是if语句的简略写法
1.2 三元表达式的语法格式
条件成立时要返回的值 if 条件 else 条件不成立时要返回的值
1.3 实例
# 针对以下需求:返回较大值
def func(x,y):
if x > y:
return x
else:
return y
res=func(1,2)
print(res)
# 使用三元表达式完成
x=1
y=2
res=x if x > y else y
print(res)
def func():
res="是真的" if 'egon' == 'egon' else "是假的"
return res
2 生成式
2.1 列表生成式
列表生成式可以快速创建一个列表
2.1.1 列表生成式的语法格式
lis = [放入列表的元素 for 可迭代对象元素 in 可迭代对象 if 条件]
如果不写if 条件相当于if True
2.1.2 列表生成式的实例
# 不使用列表生成式取出所有dsb
l = ['alex_dsb', 'lxx_dsb', 'wxx_dsb', "xxq_dsb", 'egon']
new_l=[]
for name in l:
if name.endswith('dsb'):
new_l.append(name)
# 使用列表生成式取出所有dsb
l = ['alex_dsb', 'lxx_dsb', 'wxx_dsb', "xxq_dsb", 'egon']
new_l=[name for name in l if name.endswith('dsb')]
print(new_l)
# 把所有小写字母全变成大写
new_l=[name.upper() for name in l]
print(new_l)
# 把所有的名字去掉后缀_dsb
# 方法一:
new_l=[name.replace('_dsb','') for name in l]
print(new_l)
# 方法二:
new_l=[name.split("_")[0] for name in l]
print(new_l)
2.2 字典生成式
字典生成式可以快速创建一个字典
2.2.1 字典生成式的语法格式
dic = {放入字典的key:放入字典的value for 可迭代对象元素 in 可迭代对象 if 条件}
如果不写if 条件相当于if True
2.2.2 字典生成式的实例
keys=['name','age','gender']
dic={key:None for key in keys}
print(dic)
items=[('name','egon'),('age',18),('gender','male')]
res={k:v for k,v in items if k != 'gender'}
print(res)
2.3 集合生成式
集合生成式可以快速创建一个集合
2.3.1 集合生成式的语法格式
s = {放入集合的元素 for 可迭代对象元素 in 可迭代对象 if 条件}
如果不写if 条件相当于if True
2.3.2 字典生成式的实例
keys=['name','age','gender']
set1={key for key in keys}
print(set1,type(set1))
# {'gender', 'age', 'name'} <class 'set'>
2.4 生成器表达式
生成器表达式可以快速创建一个生成器
2.4.1 生成器表达式的语法格式
g=(放入生成器的元素 for 可迭代对象元素 in 可迭代对象 if 条件)
如果不写if 条件相当于if True
2.4.2 字典生成式的实例
g=(i for i in range(10) if i > 3)
print(g,type(g))
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
# 计算文件中字符的总数量
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)
1