列表生成式与生成器表达式

示例:

#1、列表生成式

l=[]
for i in range(6):
    l.append('egg%s' %i)
print(l)
''' ['egg0', 'egg1', 'egg2', 'egg3', 'egg4', 'egg5'] '''


l=['egg%s' %i for i in range(6)]
print(l)
l=['egg%s' %i for i in range(15) if i > 10]
print(l)

'''
['egg0', 'egg1', 'egg2', 'egg3', 'egg4', 'egg5']
['egg11', 'egg12', 'egg13', 'egg14']
'''

#2、生成器表达式
l=('egg%s' %i for i in range(15) if i > 10)
print(next(l))
print(next(l))
print(next(l))

'''
egg11
egg12
egg13
'''

#3、练习题
names=['egon','alex_sb','wupeiqi','yuanhao','lxx']
res=map(lambda x:x.upper(),names) #使用map函数把names列表中的值经过lambda匿名函数变为大写
names=list(res)
print(names)
''' ['EGON', 'ALEX_SB', 'WUPEIQI', 'YUANHAO', 'LXX'] '''

#列表生成器
names=['egon','alex_sb','wupeiqi','yuanhao','lxx']
names=[name.upper() for name in names]
print(names)
''' ['EGON', 'ALEX_SB', 'WUPEIQI', 'YUANHAO', 'LXX'] '''


names=['egon','alex_sb','wupeiqi','yuanhao','lxx']
names=[len(name) for name in names if not name.endswith('sb')]
print(names)
''' [4, 7, 7, 3] '''

# nums=[]
# with open('a.txt','r',encoding='utf-8') as f:
#     for line in f:
#         # print(len(line))
#         nums.append(len(line))
# 
# print(max(nums))


with open('a.txt','r',encoding='utf-8') as f:
    # nums=(len(line) for line in f)

    # print(nums)
    # print(next(nums))
    # print(next(nums))
    # print(next(nums))
    # print(max(nums))
    # print(max(nums))


    # max((len(line) for line in f))
    print(max(len(line) for line in f))

 

posted @ 2020-07-16 09:39  zh_小猿  阅读(180)  评论(0编辑  收藏  举报