1.三元表达式
#example1
x = 10
y = 20
res = x if x > y else y
print(res)
#example2
name = 'abc'
res = 'y' if name == 'abc' else 'n'
print(res)
2.列表推导式
#传统方法
l = []
for i in range(1,11):
l.append('egg'+str(i))
print(l)
#列表推导式方法
l1=['egg' + str(i) for i in range(1,11)]
print(l1)
l2 = ['egg' + str(i) for i in range(1,11) if i > 6]
print(l2)
3. 生成器表达式
g =('egg' + str(i) for i in range(1,))
print(g) #<generator object <genexpr> at 0x000001993140CE60>
print(next(g))
4. 练习
1)将names=['egon','alex_sb','wupeiqi','yuanhao']中的名字全部变大写
names=['egon','alex_sb','wupeiqi','yuanhao']
names = [name.upper() for name in names]
print(names) #['EGON', 'ALEX_SB', 'WUPEIQI', 'YUANHAO']
2)将names=['egon','alex_sb','wupeiqi','yuanhao']中以sb结尾的名字过滤掉,然后保存剩下的名字长度
names=['egon','alex_sb','wupeiqi','yuanhao']
name1=[name for name in names if not name.endswith('sb')]
print(name1) #['egon', 'wupeiqi', 'yuanhao']
name_len=[len(name) for name in names if not name.endswith('sb')]
print(name_len) #[4, 7, 7]