Python列表、字典的筛选

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python
#coding:utf-8

from random import randint

"""
列表筛选
生成一个有20个随机数的数组 data
从 data 列表中筛选出大于0的数字
"""

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

print data

## 迭代
def test1(d):
s = []
for x in data:
if x >=0:
s.append(x)
return s

## 用filter
def test2(d):
return filter(lambda x:x>=0,d)

## 用列表解析
def test3(d):
return [x for x in data if x>=0]

print test1(data)
print test2(data)
print test3(data)

## 迭代最慢、列表解析最快

"""
字典的筛选
生成键值在56-100之间的随机数10个
找出大于90的数
"""

data = {x:randint(56,100) for x in xrange(1,11)}
print data

def test4(d):
return {k:v for k,v in d.iteritems() if v>=90}

print test4(data)

输出:

1
2
3
4
5
6
7
[61, -31, 2, -45, -1, 19, -41, -8, -17, 48]
[61, 2, 19, 48]
[61, 2, 19, 48]
[61, 2, 19, 48]
{1: 59, 2: 99, 3: 97, 4: 83, 5: 89, 6: 79, 7: 69, 8: 58, 9: 73, 10: 58}
{2: 99, 3: 97}

关注公众号 尹安灿