python中的数据过滤

1.使用filter函数

In [1]: from random import randint

In [2]: data = [randint(-10,10) for _ in xrange(10)]

In [3]: data
Out[3]: [10, -4, 8, -10, 2, 5, -1, 2, -9, 0]

In [4]: filter?
Docstring:
filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true.  If
function is None, return the items that are true.  If sequence is a tuple
or string, return the same type, else return a list.
Type:      builtin_function_or_method

In [5]: filter(lambda x : x >= 0, data)
Out[5]: [10, 8, 2, 5, 2, 0]

2.使用列表解析

In [9]: [i for i in data if i >= 0]
Out[9]: [10, 8, 2, 5, 2, 0]

In [10]: timeit 

In [11]: timeit [i for i in data if i >= 0]
1000000 loops, best of 3: 1.29 µs per loop

In [13]: timeit filter(lambda x : x >= 0, data)
100000 loops, best of 3: 1.9 µs per loop

列表解析速度比filter函数速度快,使用for迭代去判断的方法最慢

3.字典解析

In [15]: d = {x: randint(60,100) for x in xrange(1,21)}

In [16]: d.keys()
Out[16]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

In [17]: {k: v for k, v in d.iteritems() if v > 90}
Out[17]: {7: 99, 9: 97, 11: 91, 13: 94, 17: 98, 20: 96}

In [18]: 

4 . 集合解析

In [18]: s = set(data)

In [19]: s
Out[19]: {-10, -9, -4, -1, 0, 2, 5, 8, 10}

In [20]: {x for x in s if x % 3 == 0}
Out[20]: {-9, 0}

In [21]: 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值