列表过滤

在ipython2中

In [1]: from random import randint  
In [11]: data = [randint(-10,10) for _ in xrange(20)] # randint(-10,10) 首尾都包含

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

In [13]: filter(lambda x:x>=0 ,data)
Out[13]: [9, 0, 7, 1, 0, 5, 8, 3, 4]

In [14]: [ x for x in data if x>=0]
Out[14]: [9, 0, 7, 1, 0, 5, 8, 3, 4]

# 1纳秒(ns)=10^-9 秒  1 微秒(us)=10^-6 秒    1 毫秒 (ms)=10^-3 秒  列表解析用时:703ns filter 用时:1.78 µs=1780ns 所以列表解析更快
In [15]: timeit [x for x in data if x>=0]
The slowest run took 14.53 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 703 ns per loop

In [16]: timeit filter(lambda x:x>=0 ,data)
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.78 µs per loop

以上两种都比新建列表迭代更快

字典解析 python ** 注意python2的字典有iteritems(),python3没有

In [20]: student = {x:randint(60,100) for x in xrange(1,21)
    ...: }

In [21]: student
Out[21]:
[(1, 84),  (2, 83),  (3, 60),  (4, 67), (5, 76), (6, 62), (7, 92), (8, 75), (9, 95), (10, 100), 
 (11, 70), (12, 84), (13, 60), (14, 74), (15, 70), (16, 76), (17, 68), (18, 93), (19, 74), (20, 81)]

In [25]: student.items()
Out[25]:
[(1, 84),  (2, 83),  (3, 60),  (4, 67), (5, 76), (6, 62), (7, 92), (8, 75), (9, 95), (10, 100), 
 (11, 70), (12, 84), (13, 60), (14, 74), (15, 70), (16, 76), (17, 68), (18, 93), (19, 74), (20, 81)]

In [28]: gt_80 = {k:v for k,v in student.items() if v>80 }  # items()

In [29]: gt_80
Out[29]: {1: 84, 2: 83, 7: 92, 9: 95, 10: 100, 12: 84, 18: 93, 20: 81}

In [30]: gt_80 = {k:v for k,v in student.iteritems() if v>80 }  # student.iteritems()和items,

In [31]: gt_80
Out[31]: {1: 84, 2: 83, 7: 92, 9: 95, 10: 100, 12: 84, 18: 93, 20: 81}

集合

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

In [33]: set_data = set(data)

In [34]: set_data
Out[34]: {-10, -9, -8, -7, -5, -3, -1, 0, 1, 3, 4, 5, 7, 8, 9}


In [37]: {x for x in set_data if x>=0 }
Out[37]: {0, 1, 3, 4, 5, 7, 8, 9}

In [38]:
posted @ 2021-04-16 20:28  ty1539  阅读(15)  评论(0编辑  收藏  举报