python进阶之 ——三元表达式、列表推导式、生成器表达式
三元表达式
def max2(x,y): if x > y: return x else: return y res=max2(10,20)
x=10 y=20 # res=x if x > y else y # print(res) #20 res='OK' if False else 'No' print(res) #No
列表推导式
#1、示例 egg_list=[] for i in range(10): egg_list.append('鸡蛋%s' %i) egg_list=['鸡蛋%s' %i for i in range(10)] #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) #3、优点:方便,改变了编程习惯,可称之为声明式编程
生成器表达式
把列表推导式的[]换成()就是生成器表达式
1.列表生成式
l=[] # for i in range(10): # if i > 4: # l.append(i**2) l=[i**2 for i in range(10) if i > 4] print(l) names=['abcd','cmdb_sb','kevin_sb','hxx_sb','cxx_sb'] # sbs=[] # for name in names: # if name.endswith('sb'): # sbs.append(name) sbs=[name.upper() for name in names if name.endswith('sb')] print([name.upper() for name in names]) #['ABCD', 'CMDB_SB', 'KEVIN_SB', 'HXX_SB', 'CXX_SB']
2.字典生成式
res={i:i**2 for i in range(10) if i > 3} print(res) # {4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
print({i for i in 'hello'}) # {'l', 'h', 'o', 'e'}