python 数据结构与方法

关于python中数据的筛选进阶

列表处理

1
2
3
from random import randint
# 创建随机list 过滤负数和零
data = [randint(-10, 10) for _ in range(10)]
1
data
[4, -6, -9, 3, 10, -10, 2, 1, -2, -6]
1
[x for x in data if x > 0]
[4, 3, 10, 2, 1]
1
list(filter(lambda x: x > 0, data))
[4, 3, 10, 2, 1]

测试两种方式的速度

1
timeit [x for x in data if x > 0]
617 ns ± 22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1
timeit filter(lambda x: x > 0, data)
244 ns ± 1.45 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

字典处理

1
2
3
4
# demo: 10人身高问题

data = {x: randint(140, 190) for x in range(1, 10)}
data
{1: 161, 2: 165, 3: 181, 4: 158, 5: 173, 6: 160, 7: 185, 8: 152, 9: 171}
1
2
# 过滤身高超过175的人
{key: value for key, value in data.items() if value > 175}
{3: 181, 7: 185}
1
timeit {key: value for key, value in data.items() if value > 175}
931 ns ± 19.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1
set(filter(lambda y: y > 175, data.values()))
{181, 185}

集合处理

1
2
data = {x for x in range(20)}
data
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
1
{x for x in data if x % 3 == 0}
{0, 3, 6, 9, 12, 15, 18}