from functools import reduce # 列表推导式:[表达式 for 变量 in 数据列表 if 表达式] # 一行打印1~100之间的偶数 l = [i for i in range(1,101) if i % 2 == 0] print(l) # 1到100所有平方的列表 l = [i * i for i in range(1,101)] print(l) # 字典推导式 # {字典内容 + 循环条件 + 判断条件} # {"a":1,"b":2,"c":3}要求将键值倒置 dic = {"a":1,"b":2,"c":3} l = {v : k for k, v in dic.items()} print(l) # 新字典数值平方 l = {k : v * v for k, v in dic.items()} print(l) # 新字典数值平方,key大写 l = {k.upper() : v * v for k, v in dic.items()} print(l) # 匿名函数 bar = lambda x,y:x+y ret = bar(3,1) print(ret) ret = (lambda x,y:x+y)(3,1) print(ret) # 高阶函数:filter map reduce l = [1,2,3,4,5,6,7,8] # 保留所有的偶数 # 方法1 l1 = [i for i in l if i % 2 == 0] print(l1) # 方法2 def funca(item): if item % 2 == 0: return True else: return False l1 = list(filter(funca,l)) print(l1) # 方法3 l1 = list(filter(lambda i : i % 2 == 0,l)) print(l1) # 计算列表平方 # 方法1 def bar(item): return item * item l1 = list(map(bar, l)) print(l1) # 方法2 l1 = list(map(lambda i : i * i, l)) print(l1) # 计算1~100的和(reduce) # 方法1 ret = sum([i for i in range(1,101)]) print(ret) # 方法2 def func(x,y): return x+y ret = reduce(func, [i for i in range(1,101)]) print(ret) # 方法3 ret = reduce(lambda x,y:x+y,range(1,101)) print(ret) # 按照index = 1从大到小排序 l = [("yuan",22),("yuan1",21),("yuan2",25)] l1 = sorted(l,key = lambda i:i[1],reverse=True) print(l1) # 按照value从大到小排序 l = [{"age":22},{"age":33},{"age":29}] l1 = sorted(l,key= lambda i : i["age"],reverse=True) print(l1) # zip函数 l1 = [1,2,3] l2 = (4,5,6) l = list(zip(l1,l2)) print(l) # [(1, 4), (2, 5), (3, 6)] name = ["yuan","rain","alvin"] ages = [18, 22, 33] l = list(zip(name,ages)) print(l) # [('yuan', 18), ('rain', 22), ('alvin', 33)] ret = dict(l) print(ret) # {'yuan': 18, 'rain': 22, 'alvin': 33}