列表数组集合解析
from random import randint a = [randint(-10, 10) for _ in range(10)] # -10 -- 10 随机生成长度为10的列表 # print(a) # 赛选出正数 # 方案一: # 速度最慢 z_list = [] for i in a: if i >= 0: z_list.append(i) print(z_list) # 方案二: 速度中 p = filter(lambda x: x >= 0, a) print(list(p)) print(type(p)) # 方案三:速度最 l = [x for x in a if x >= 0] # 列表解析 print(l) # 字典解析 t_dict = {k: randint(1, 100) for k in range(1, 21)} # 随机生成一个字典 print(t_dict) s_dict = {k: v for k, v in t_dict.items() if v >= 60} print(s_dict) # 集合解析 t_set = {x for x in range(1, 21) if x % 3 == 0} print(t_set) # 匿名函数lambda s = lambda x:x*x print(s(2)) # map 方法 b_list = [1,2,3,4] mm = map(lambda x:x if x >2 else None,b_list) print(list(mm))