6.13 三元表达式
def my_max(x,y): # Low的写法 if x >= y: return x else: return y x=10 y=20 res=x if x >= y else y # 三元表达式 print(res) name=input('>>: ').strip() res='Sb' if name == 'alex' else 'NB' # 三元表达式 print(res)
6.14 列表推导式和生成器表达式
6.14.1 列表推导式
1、列表推导式,用[]
# 第一种 列表推导式 l=['egg'+str(i) for i in range(1,11)] print(l) #l=[] #for i in range(1,11): # res='egg'+str(i) # l.append(res) #print(l) # 第二种 列表推导式 l1=['egg'+str(i) for i in range(1,11) if i >= 6] print(l1) #l1=[] #for i in range(1,11): # if i >= 6: # l1.append('egg'+str(i))
2、语法:
#语法 [expression for item1 in iterable1 if condition1 for item2 in iterable2 if condition2 ... for itemN in iterableN if conditionN ] 类似于 res=[] for item1 in iterable1: if condition1: for item2 in iterable2: if condition2 ... for itemN in iterableN: if conditionN: res.append(expression)
6.14.2 生成器表达式
把列表推导式的[]换成()就是生成器表达式
优点:省内存,一次只产生一个值在内存中
g=('egg'+str(i) for i in range(0,100000000000000000000000)) #生成器表达式 print(g) print(next(g)) print(next(g)) print(next(g))
6.14.3 练习
names=['egon','alex_sb','wupeiqi','yuanhao'] names=[name.upper() for name in names] # 列表内容都大写 print(names) sbs=[name for name in names if name.endswith('sb')] # 筛选以sb结尾的名字 print(sbs) print(max([1,2,3,4,5])) # max的参数可以是可迭代器的对象 g=(i for i in range(10)) print(max(g)) # max的参数可以是生成器 with open('a.txt','r',encoding='utf-8') as f: print(sum(len(line) for line in f)) # 文件的长度