三元表达式,列表生成式,字典生成式,生成器表达式
'''
def max2(x,y):
if x>y:
return x
else:
return y
print(max(2,5))
x = 10
y = 30
res = x if x > y else y####上面函数的功能一行就可以搞定
print(res)
###条件满足的结果,放在最左边,条件不满足的结果,放在右边,中间是条件
'''
列表生成式
ls = []
for i in range(10):
res = 'egg%s' %i
ls.append(res)
print(ls)
##上面代码实现的功能下面这一行就能实现,这个称之为列表时生成式
ls = ['egg%s'%i for i in range(10)]
print(ls)
num = [i for i in range(10)]
print(num)
num = [i**2 for i in range(10)]
print(num)
##后面可以加判断
num = [i for i in range(10) if i >3]
print(num) ###[4, 5, 6, 7, 8, 9]
练习题
1,将names = ['egon','alex_sb','wupeiqi','yuanhao']中的名字全部变成大写
names = ['egon','alex_sb','wupeiqi','yuanhao']
new_names = []
for name in names:
new_names.append(name.upper())
print(new_names)
new_names = [name.upper()for name in names ]
print(new_names)
2,将names = ['egon','alex_sb','wupeiqi','yuanhao']中以sb结尾的名字过滤掉,然后保存剩下的名字长度
names = ['egon','alex_sb','wupeiqi','yuanhao']
for i in names:
if i.endswith('sb'):
names.remove(i)
print(names,len(names))
new_names = [i for i in names if not i.endswith('sb') ]
print(new_names,len(new_names))
字典生成式:
dic = {i:i**2 for i in range(10) if i > 0}
print(dic)
user = [('egon','123'),('ales','456'),('www','789')]
###要求转换为字典
dic = {}
for a in user:
dic[a[0]] =a[1]
print(dic)
dic = {a[0]:a[1] for a in user}
print(dic)
生成器表达式
生成器表达式只是在列表生成式的基础上将中括号换成了小括号
g = ( i for i in range(10000000000000000000))
print(g)
print(next(g))
print(next(g))
###生成器表达式就是要生成一个有无限多数据的数据,不管有多大,都可以实现,
###如果不这样做的话,单纯的用列表生成式,系统内存会炸掉,也就是占用很大很大的内存
需求:求文件a.txt中最长的行的长度(长度按照字符个数算,需要使用max函数)
提示:res = max([1,2,3,4,5,6,7,8,9])###里面可以放一个可迭代对象,工作原理和for循环类似
print(res)
'''
print('================================================')
with open('a.txt',mode = 'r',encoding = 'utf-8') as f:
ls = (len(line) for line in f )
print(ls)
# print(max(ls))