{{ cat }}'s docs

1.1.0 筛选数据(列表、字典、集合)高级用法


1. 列表解析筛选数据

>>> from random import randint

>>> data = [randint(-10, 10) for _ in xrange(10)]

>>> data
[10, -6, 8, -10, -9, 7, -4, 6, 2, -2]

>>> filter(lambda x: x >= 0, data)
[10, 8, 7, 6, 2]

>>> [x for x in data if x >= 0]
[10, 8, 7, 6, 2]


## 对比速度
>>> timeit filter(lambda x: x >= 0, data)
The slowest run took 5.03 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 995 ns per loop

>>> timeit [x for x in data if x >= 0]
The slowest run took 7.04 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 440 ns per loop
## 对比结果,发现列表解析的方式快

2. 字典解析筛选数据

>>> score
{'harry': 59, 'jack': 90, 'tom': 78, 'zack': 20}

>>> {k: v for k, v in score.iteritems() if v >= 60}
{'jack': 90, 'tom': 78}

3. 集合解析筛选数据

>>> s
{-10, -9, -6, -4, -2, 2, 6, 7, 8, 10}

>>> {x for x in s if x >= 0}
{2, 6, 7, 8, 10}