python基础===如何在列表,字典,集合中根据条件筛选数据
#常见的操作如下: data = [1, 5, -3, -2, 6, 0, 9] res = [] for x in data: if x>=0: res.append(x) print(res) from random import randint #生成(-10,10)随机的十位列表 list_1 = [randint(-10, 10) for _ in range(10)] #第一种方法 list_2 = list(filter(lambda x: x>=0,list_1)) print(list_2) #第二种方法,推荐这种 list_3 = [x for x in list_1 if x >=0] print(list_3) #保留字典中大于80的值 dic_1 = {x: randint(0,100)for x in range(1,20)} print(dic_1) dic_2 = {k: v for k,v in dic_1.items() if v > 80} print(dic_2) set_1 = set(list_1) set_2 = {x for x in set_1 if x%3 == 0} print(set_2)
纸上得来终觉浅,绝知此事要躬行!