1. 从列表中过滤掉 负数
from random import randint # 随机生成列表 data = [randint(-10, 10) for _ in range(10)] print(data) #输出 [-4, -2, 2, -10, 8, 10, -6, 6, 3, -9] # 1 用 filter 实现 ret = filter(lambda x: x >= 0, data) print( list(ret)) # 输出 [2, 8, 10, 6, 3]
# 2 用列表解析实现
ret2 = [x for x in data if x >= 0]
print(ret2) # 输出 [2, 8, 10, 6, 3]
2.从字典中获取分数大于90 的人
from random import randint # 随机生成字典, {学号:分数} score = {x:randint(60,100) for x in range(1, 21)} print(score) # {1: 97, 2: 94, 3: 86, 4: 83, 5: 90, 6: 85, 7: 100, 8: 68, 9: 96, 10: 67, 11: 65, 12: 98, 13: 84, 14: 69, 15: 62, 16: 73, 17: 79, 18: 70, 19: 77, 20: 99} ret = {k : v for k, v in score.items() if v > 90} print(ret) # {1: 97, 2: 94, 7: 100, 9: 96, 12: 98, 20: 99}
3.能被3整除的集合
ret_set = {x for x in set1 if x % 3 == 0}