python数据结构-如何在列表、字典、集合中根据条件筛选数据

如何在列表、字典、集合中根据条件筛选数据

问题举例:

过滤列表[1, 2, 5, -1, 9, 10]中的负数

筛选字典{“zhangsan”:97, "lisi":80, "wangwu":60, "liqiang":91}中的值高于90的键值对

筛选集合{89, 70, 60, 80, 90}中能被3整除的元素

 

列表

一般遇到这种问题,我们首先会想到用for循环的方式去解决

(1)for循环

from random import randint
nums = [randint(-10, 10) for _ in range(20)] #生成一个列表
res_list = []
for ele in nums:
    if ele > 0:
        res_list.append(ele)

但是这种方式并不pythonic

 

(2)列表解析

from random import randint
nums = [randint(-10, 10) for _ in range(20)]
res_list = [ele for ele in nums if ele > 0] #list comprehension

 

(3)filter函数

from random import randint
nums = [randint(-10, 10) for _ in range(20)]
res_filter = filter(lambda x: x > 0, nums) #filter
res_list = list(res_filter)

 

字典

(1)字典解析

from random import randint
grade_info = {"stu%d" % i: randint(50, 100) for i in range(10)}
res_dict = {k: v for k, v in grade_info.items() if v > 70}

 

(2)filter函数

 

集合

集合解析

from random import randint
nums_set = {randint(10, 20) for _ in range(20)}
nums_res = {ele for ele in nums_set if ele % 3 == 0}

 

参考资料:python3实用编程技巧进阶

猜你喜欢

转载自www.cnblogs.com/marton/p/10720744.html
0条评论
添加一条新回复