1.过滤掉列表中小于0的数据
a = [1,-2,3,4,-8,-5,-3,6,9]
(1) 一般方式
a = [1,-2,3,4,-8,-5,-3,6,9]
b = []
for x in a:
if x >= 0:
b.append(x)
(2)使用filter函数
>>> a = [1,-2,3,4,-8,-5,-3,6,9]
>>> a = filter(lambda x:x >=0,a)
>>> a
<filter object at 0x036168F0>
>>> b = []
>>> for i in a:
... b.append(i)
...
>>> b
[1, 3, 4, 6, 9]
(2)列表解析:(运行速度快,通常使用列表解析方法进行筛选)
>>> a = [1,-2,3,4,-8,-5,-3,6,9]
>>> b = [x for x in a if x >0]
>>> b
[1, 3, 4, 6, 9]
2.筛选字典
dic_a = {‘wyf’:11,’ysl’:22,’ws’:33,’djf’:44,’zjh’:55} 筛选出value值高于25的键值对
>>> dic_a = {'wyf':11,'ysl':22,'ws':33,'djf':44,'zjh':55}
>>> dic_a
{'wyf': 11, 'ysl': 22, 'ws': 33, 'djf': 44, 'zjh': 55}
>>> dic_b = {k: v for k, v in dic_a.items() if v > 25}
>>> dic_b
{'ws': 33, 'djf': 44, 'zjh': 55}
3.集合
筛选出集合中能被三整除的数据
>>> set_a = {2,3,5,66,7,2,9,5}
>>> set_b = {x for x in set_a if x % 3 == 0}
>>> set_b
{9, 66, 3}
>>>