1.过滤函数filter()
对容器中的元素进行过滤处理
filter(function, iterable)
function 为一个提供过滤条件的函数,返回布尔值
iterable是容器类型数据
在调用filter时,iterable会被遍历,元素逐一传入function中,function返回True,元素被保留,否则元素被过滤。遍历完成,保留下来的元素被放入新的容器。
filter的返回值不是列表,需要列表类型的返回数据可通过list()进行转换
# coding=utf-8
#过滤掉小于等于50的数字
def f(x):
return x>50
data = [12,66,80,42,90,52,60,43,81,76]
filtered = filter(f,data)
print(type(filtered))
data = list(filtered)
print(data)
D:\anaconda\python.exe
<class 'filter'>
[66, 80, 90, 52, 60, 81, 76]
Process finished with exit code 0
2.映射函数map()
用于对容器中的元素进行映射(变换)
map(function, iterable)
function 提供变换规则,返回变换以后的元素
iterable时容器类型的数据
在调用map函数时,iterable被遍历,逐一传入function进行变换
# coding=utf-8
#对容器内每个数乘2
def f(x):
return x*2
data = [12,66,80,42,90,52,60,43,81,76]
mapped = map(f,data)
print(type(mapped))
data = list(mapped)
print(data)
D:\anaconda\python.exe
<class 'map'>
[24, 132, 160, 84, 180, 104, 120, 86, 162, 152]
Process finished with exit code 0