实际案例
在实际开发过程中,常常遇到如下几种情况:
- 过滤掉列表[3, 9, -1, 10, 20, -2, ...]中的负数;
- 筛选出字典{‘Jack’:79, 'Jim':88, 'Lucy':92, ...}中值高于90的键值对;
- 筛选出集合{77, 89, 32, 20, ...}中能被3整除的元素。
故应学会在列表、字典和集合中根据条件筛选数据。
# -*- coding: utf-8 -*- from random import randint __author__ = 'songhao' # 生成一个10个元素的列表,范围从10 到-10之间 data = [randint(-10,10) for i in range(10)] # 普通做法 newdata = [] # print(data) for i in data: # print(i) if i >= 0: print(i, "数值大于等于零") newdata.append(i) else: print(i, "数值小于零") print(newdata, "过滤后的数值")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# -*- coding: utf-8 -*-
from
random
import
randint
__author__
=
'songhao'
# 生成一个10个元素的列表,范围从10 到-10之间
data
=
[
randint
(
-
10
,
10
)
for
i
in
range
(
10
)
]
# 普通做法
newdata
=
[
]
# print(data)
for
i
in
data
:
# print(i)
if
i
>=
0
:
print
(
i
,
"数值大于等于零"
)
newdata
.
append
(
i
)
else
:
print
(
i
,
"数值小于零"
)
print
(
newdata
,
"过滤后的数值"
)
|
# filter 过滤 列表
# filter 过滤 """ In [91]: filter? Init signature: filter(self, /, *args, **kwargs) Docstring: filter(function or None, iterable) --> filter object Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true. Type: type """ newdata1 = filter(lambda x: x > 0, data) # 注意返回值 Return an iterator yielding those items of iterable for which function(item) print(list(newdata1), "filter方法解决")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
# filter 过滤
"""
In [91]: filter?
Init signature: filter(self, /, *args, **kwargs)
Docstring:
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
Type: type
"""
newdata1
=
filter
(
lambda
x
:
x
>
0
,
data
)
# 注意返回值 Return an iterator yielding those items of iterable for which function(item)
print
(
list
(
newdata1
)
,
"filter方法解决"
)
|
# 列表解析式 过滤列表,也是我最喜欢的方式
# 列表解析式 过滤,也是我最喜欢的方式 newdata2 = [x for x in data if x > 0] print(newdata2, '列表解析式过滤')
1
2
3
4
5
|
# 列表解析式 过滤,也是我最喜欢的方式
newdata2
=
[
x
for
x
in
data
if
x
>
0
]
print
(
newdata2
,
'列表解析式过滤'
)
|
# 返回结果
/usr/local/bin/python3 /Users/songhao/Desktop/bd/d1.py -10 数值小于零 5 数值大于等于零 5 数值大于等于零 2 数值大于等于零 -7 数值小于零 5 数值大于等于零 2 数值大于等于零 5 数值大于等于零 -10 数值小于零 -5 数值小于零 [5, 5, 2, 5, 2, 5] 过滤后的数值 [5, 5, 2, 5, 2, 5] filter方法解决 [5, 5, 2, 5, 2, 5] 列表解析式过滤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/
usr
/
local
/
bin
/
python3
/
Users
/
songhao
/
Desktop
/
bd
/
d1
.
py
-
10
数值小于零
5
数值大于等于零
5
数值大于等于零
2
数值大于等于零
-
7
数值小于零
5
数值大于等于零
2
数值大于等于零
5
数值大于等于零
-
10
数值小于零
-
5
数值小于零
[
5
,
5
,
2
,
5
,
2
,
5
]
过滤后的数值
[
5
,
5
,
2
,
5
,
2
,
5
]
filter方法解决
[
5
,
5
,
2
,
5
,
2
,
5
]
列表解析式过滤
|