一、三元表达式
def max(x,y): return x if x>y else y print(max(10,12)) name=input('>>>') res='sb' if name=='alex' else 'nb' print(res) ''' name=input('>>>') res='sb' if name=='alex': print(res') else: print('nb') '''
二、列表推导
egg_list=[] for i in range(10): egg_list.append('鸡蛋%s'%i) print(egg_list) egg_list=['鸡蛋%s'%i for i in range(10)] print(egg_list) ''' 优点是方便、改变了编程习惯,可被称为声明式编程 '''
三、生成器表达式
''' 把列表推导中的[]换成()生成器表达式 其优点是节省内存,一次在内存中只产生一个值 ''' bamboo=('竹节%s节'%i for i in range(1,11)) print(bamboo)#生成器表达式内存地址 print(next(bamboo)) print(list(bamboo)) names=['cindy','sara','chengjie','mark'] li=(i.capitalize() for i in names) print(list(li))#['Cindy', 'Sara', 'Chengjie', 'Mark'] with open('a.txt',encoding='utf-8') as f: print(max(len(line) for line in f))# 选出最长一行 print(sum(len(line) for line in f)) info=[line.split() for line in f] print(info)
四、递归
items=[1,[2,[3,[4,[5,[6,[7,[8,[9,[0,]]]]]]]]]] def tell(l): for item in l: if type(item) is not list: print(item) else: tell(item) tell(items) def age(n): if n==1: return 18 return age(n-1)+2 print(age(5))#26 def age(n): return 18 if n==1 else age(n-1)+2 print(age(5))#26 def foo(): print('from foo') foo() foo()#递归报错,超过最大限制
五、匿名函数
f=lambda x,n:x**n print(f) print(f(2,4)) print(3^6)
六、内置函数
salaries={ 'aa':1200, 'bb':342, 'cc':3456, 'dd':3455 } def get(k): return salaries[k] print(max(salaries,key=get))#key必须是个函数,该函数必须有返回值 #max() print(max(salaries,key=lambda k:salaries[k])) #min() print(min(salaries,key=lambda k:salaries[k])) #sorted()默认升序即从小到大,以列表形式返回 salaries=sorted(salaries,key=lambda k:salaries[k]) print(salaries) #sorted()降序即从大到小 salaries=sorted(salaries,key=lambda k:salaries[k],reverse=True) print(salaries) res=map(lambda k:salaries[k],salaries)#得到map的映射对象,是个迭代器 #print(res.__next__()) print(list(res)) name=['aa','bb','cc'] res=map(lambda x:x+'__nb' if x=='cc' else x+'__sb',name) print(list(res))#['aa__sb', 'bb__sb', 'cc__nb'] from functools import reduce l=['it','name','is','mage','mage','is','a','little','dog'] res=reduce(lambda x,y:x+' '+y,l) print(res) names=['aa_','bb_','cc*','dd_'] res=filter(lambda x:True if x.endswith('_') else False,names) print(list(res)) res=filter(lambda x:x.endswith('_'),names) print(list(res)) num=[1,3,3,65,3,4,6,8,5,65] res=filter(lambda x:x>22,num) print(list(res)) print(ord('A'))#65 print(chr(77))#M print(bytes('大王叫我来巡山',encoding='utf-8')) #b'\xe5\xa4\xa7\xe7\x8e\x8b\xe5\x8f\xab\xe6\x88\x91\xe6\x9d\xa5\xe5\xb7\xa1\xe5\xb1\xb1' print(abs(-11))#11 print(all(['a',0,1]))#False print(any(['a',0,1]))#True print(ascii('花花世界'))#'\u82b1\u82b1\u4e16\u754c' print(bin(3))#0b11 print(bool(0))#False print(callable(int))#True print(classmethod(int))#<classmethod object at 0x00000166BD7BB278>