# 数据类型:int bool float等等 # 数据结构:dict tuple list set str # 内置函数 # l =[1,2,3,4,5] # l.reverse() # print(l) # l = [1,2,3,4,5] # l2 = reversed(l) #保留原列表,返回一个反向的迭代器 # print(l2) # l = [1,2,3,4,5,6,7,8,9] # sli = slice(1,5,2) # print(l[sli]) #切片函数 # print(format('text','<20')) #左对齐 # print(format('text','>20')) #右对齐 # print(format('text','^20')) #居中 # bytes--转换成bytes类型 # 拿到的是gbk编码,想转化成utf-8编码 # 运用范围: # 网络编程 # 照片和视频 # html爬取到的内容 # print(bytes('你好',encoding='gbk')) #unicode转换成gbk的bytes # print(bytes('你好',encoding='utf-8')) #unicode转换成utf-8的bytes # b_array = bytearray('你好',encoding='utf-8') # print(b_array) #转换成字节类型的数组 # print(b_array[0]) # print(ord('好')) #返回ascii或unicode值 # print(ord('a')) # print(ascii('a')) # print(ascii('豪')) # name = 'egg' # print('你好%r'%name) # print(repr('dfasfd')) # print(all(['a',1,45,6,67,0])) #判断是否全部为True # print(any(['a',1,45,6,67,0])) #判断是否有一个为True # zip()拉链方法 # l=[1,2,3,4,5] # l2=['a','b','c'] # l3=['*','**','&&'] # l4={'k1':3,'k2':3,'k3':3} # ret = zip(l,l2,l3,l4) # print(ret) #返回一个迭代器 # for i in ret: # print(i) #返回的是一个元组 # filter(function, iterable)过滤函数 # def is_odd(x): # return x%2 == 1 # ret = filter(is_odd,[1,2,3,4,5,6]) #返回迭代器 # for i in ret: # print(i) # 其实就是列表解析[i for i in [1,2,3,4,5,6] if i%2 == 1] # def is_srt(s): # return s and str(s).strip() # ret = filter(is_srt,[1,2,3,4,5,' ','python']) # for i in ret: # print(i) # l = [1,2,3,4,-43,-5] # l.sort(key=abs) # print(l)#在原有的列表上排序,并可指定排序方式 # l = [1,2,3,4,-43,-5] # print(sorted(l,key=abs,reverse=True)) #生成一个新列表,不改变原有列表但是会占内存 # print(l) # 小练习:用列表按照每个元素的长度排序 # l = ['dsfds','sdafsdfas','sd'] # new_l = sorted(l,key=len,reverse=True) # print(new_l) # 匿名函数--只能写在一行 # def add(x,y): # return x+y # add=lambda x,y:x+y # print(add(99,1)) # 按照value值进行排序 # dic = {'k1':10,'k2':100,'k3':1000} # def func(key): # return dic[key] # print(max(dic,key=func))错误 # print(max(dic,key=lambda key:dic[key])) # ret = map(abs,[-1,-4,4,35]) # for i in ret: # print(i) # def func(x): # return x**2 # ret = map(func,[-1,-4,4,35]) # for i in ret: # print(i) # 就等于 # ret = map(lambda x:x**2,[-1,-4,4,35]) # for i in ret: # print(i) # 筛选大于10的数 # res = filter(lambda x:x>10,[23,4,45,65,7,67]) # for i in res: # print(i) # 与lambda连用的内置函数--filter、map、sorted,min,max # 面试提练习 # 1.下面程序的输出结果是: # d = lambda p: p * 2 # t = lambda p: p * 3 # x = 2 # x = d(x) #x=4 # x = t(x) #x=12 # x = d(x) #x=24 # print(x) # 2.现有两元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}] # ret = zip((('a'),('b')),(('c'),('d'))) # print(list(map(lambda tup:{tup[0]:tup[1]},ret))) # 3.以下代码的输出是什么?请给出答案并解释。 # def multipliers(): # return [lambda x:i*x for i in range(4)] # print([m(2) for m in multipliers()]) # # 请修改multipliers的定义来产生期望的结果。 # def multipliers(): # return (lambda x:i*x for i in range(4)) # print([m(2) for m in multipliers()])